Skip to content

Instantly share code, notes, and snippets.

@madelinecr
Forked from anonymous/index.html
Last active December 14, 2015 05:39
Show Gist options
  • Save madelinecr/5036709 to your computer and use it in GitHub Desktop.
Save madelinecr/5036709 to your computer and use it in GitHub Desktop.
A very rudimentary binary search tree in Javascript
var tree = new Tree();
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function Tree() {
this.head = null;
}
Tree.prototype.add = function(value) {
if(this.head == null) {
this.head = new Node(value);
} else {
this.add_recursive(value, this.head);
}
}
Tree.prototype.add_recursive = function(value, node) {
if(value < node.value) {
if(node.left == null) {
node.left = new Node(value);
} else {
this.add_recursive(value, node.left)
}
} else if(value > node.value) {
if(node.right == null) {
node.right = new Node(value);
} else {
this.add_recursive(value, node.right)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment