Skip to content

Instantly share code, notes, and snippets.

@youngdze
Created October 19, 2015 06:05
Show Gist options
  • Save youngdze/8f3954450e75b9c05556 to your computer and use it in GitHub Desktop.
Save youngdze/8f3954450e75b9c05556 to your computer and use it in GitHub Desktop.
var Node = function( data, left, right ){
this.data = data;
this.left = left;
this.right = right;
};
Node.prototype.getData = function(){
return this.data;
};
var BST = function(){
this.root = null;
};
BST.prototype.insert = function( data ){
var n = new Node(data, null, null);
if(!this.root){
this.root = n;
} else{
var current = this.root;
var parent;
while(true){
parent = current;
if(data < current.data){
current = current.left;
if(!current){
parent.left = n;
break;
}
} else{
current = current.right;
if(!current){
parent.right = n;
break;
}
}
}
}
};
BST.prototype.inOrder = function( node ){
if(node){
this.inOrder(node.left);
console.log(node.getData());
this.inOrder(node.right);
}
};
BST.prototype.preOrder = function( node ){
if (node) {
console.log(node.getData());
this.preOrder(node.left);
this.preOrder(node.right);
}
};
BST.prototype.postOrder = function( node ){
if (node) {
this.postOrder(node.left);
this.postOrder(node.right);
console.log(node.getData());
}
};
BST.prototype.getMin = function(){
var current = this.root;
while(current.left) {
current = current.left;
}
return current.getData();
};
var nums = new BST();
nums.insert(39);
nums.insert(19);
nums.insert(12);
nums.insert(21);
nums.insert(10);
nums.insert(20);
nums.insert(9);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment