Skip to content

Instantly share code, notes, and snippets.

@justinobney
Created October 9, 2018 12:53
Show Gist options
  • Save justinobney/839ca5f7e5973893b9d56ebc9078fdc6 to your computer and use it in GitHub Desktop.
Save justinobney/839ca5f7e5973893b9d56ebc9078fdc6 to your computer and use it in GitHub Desktop.
bst
class Node {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
insert(value){
if(value < this.value){
if(!this.left){
this.left = new Node(value);
} else {
this.left.insert(value)
}
} else {
if(!this.right){
this.right = new Node(value);
} else {
this.right.insert(value)
}
}
}
get(value){
if(this.value === value){
return this.value;
} else if(this.left && value <= this.value){
return this.left.get(value);
} else if(this.right && value >= this.value) {
return this.right.get(value);
} else {
console.log(value);
}
}
}
class Tree {
insert(value){
if(!this.root){
this.root = new Node(value);
} else {
this.root.insert(value);
}
}
get(value){
return this.root.get(value);
}
}
const tree = new Tree();
tree.insert(15);
tree.insert(35);
tree.insert(30);
tree.insert(37);
tree.insert(38);
tree.insert(39);
tree.insert(45);
tree.insert(20);
tree.insert(27);
tree.insert(28);
tree.insert(22);
tree.insert(40);
tree.insert(25);
console.log(tree.get(45));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment