Skip to content

Instantly share code, notes, and snippets.

@seanbollin
Created February 14, 2014 07:16
Show Gist options
  • Save seanbollin/8996997 to your computer and use it in GitHub Desktop.
Save seanbollin/8996997 to your computer and use it in GitHub Desktop.
Javascript Binary Tree Impl.
var binaryTree = function(rootObj) {
var that = {};
that.key = rootObj;
that.leftChild = undefined;
that.rightChild = undefined;
that.insertLeft = function(newNode) {
if (this.leftChild === undefined) {
this.leftChild = binaryTree(newNode);
} else {
var tree = binaryTree(newNode);
tree.leftChild = this.leftChild;
this.leftChild = tree;
}
};
that.insertRight = function(newNode) {
if (this.rightChild === undefined) {
this.rightChild = binaryTree(newNode);
} else {
var tree = binaryTree(newNode);
tree.rightChild = this.rightChild;
this.rightChild = tree;
}
}
return that;
};
var treeA = binaryTree("A");
treeA.insertLeft("B");
treeA.leftChild.insertRight("D");
treeA.insertRight("C");
treeA.rightChild.insertLeft("E");
treeA.rightChild.insertRight("F");
console.log(treeA.key);
console.log(treeA.leftChild.key);
console.log(treeA.rightChild.key);
console.log(treeA.leftChild.rightChild.key);
console.log(treeA.rightChild.leftChild.key);
console.log(treeA.rightChild.rightChild.key);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment