Skip to content

Instantly share code, notes, and snippets.

@athap
Created September 6, 2014 17:17
Show Gist options
  • Save athap/9369469a79b46edc1343 to your computer and use it in GitHub Desktop.
Save athap/9369469a79b46edc1343 to your computer and use it in GitHub Desktop.
Binary tree lofic
// Represents the btree logic
var BTree = function() {
var c = document.getElementById('my-canvas');
var ctx = c.getContext('2d');
var line = new Line();
this.root = null;
var self = this;
// Getter for root
this.getRoot = function() { return this.root; };
// Adds element to the tree
this.add = function( data) {
// If root exists, then recursively find the place to add the new node
if(this.root) {
this.recursiveAddNode(this.root, null, null, data);
} else {
// If not, the add the element as a root
this.root = this.addAndDisplayNode(200, 20, 15, ctx, data);
return;
}
};
// Recurively traverse the tree and find the place to add the node
this.recursiveAddNode = function(node, prevNode, coordinateCallback, data) {
if(!node) {
// This is either node.leftCoordinate or node.rightCoordinate
var xy = coordinateCallback();
var newNode = this.addAndDisplayNode(xy.cx, xy.cy, 15, ctx, data);
line.draw(prevNode.getX(), prevNode.getY(), xy.cx, xy.cy, prevNode.getRadius(), ctx)
return newNode;
}
else {
if(data <= node.getData()) {
node.left = this.recursiveAddNode(node.left, node, node.leftCoordinate, data);
}
else {
node.right = this.recursiveAddNode(node.right, node, node.rightCoordinate, data);
}
return node;
}
};
// Adds the node to the tree and calls the draw function
this.addAndDisplayNode = function(x, y, r, ctx, data) {
var node = new Node(x, y, r, ctx, data);
node.draw();
return node;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment