Skip to content

Instantly share code, notes, and snippets.

@MathRivest
Created September 16, 2017 22:52
Show Gist options
  • Save MathRivest/8b0bc56f40befae3bc15553eb17a4d24 to your computer and use it in GitHub Desktop.
Save MathRivest/8b0bc56f40befae3bc15553eb17a4d24 to your computer and use it in GitHub Desktop.
bst-es6 created by mathrivest - https://repl.it/LMAV/0
class BST {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
insert(value) {
if (value <= this.value) {
if (!this.left) {
this.left = new BST(value);
} else {
this.left.insert(value);
}
} else if (value > this.value) {
if(!this.right) {
this.right = new BST(value);
} else {
this.right.insert(value);
}
}
}
contains(value) {
if(value === this.value) {
return true;
} else if(value < this.value) {
if(!this.left) {
return false;
} else {
return this.left.contains(value);
}
} else if(value > this.value) {
if(!this.right) {
return false;
} else {
return this.right.contains(value);
}
}
}
depthFirstTraversal(iteratorFunc) {
if(this.left) {
this.left.depthFirstTraversal(iteratorFunc);
}
iteratorFunc(this.value);
if(this.right) {
this.right.depthFirstTraversal(iteratorFunc);
}
}
}
var myBST = new BST(50);
myBST.insert(30);
myBST.insert(70);
myBST.insert(80);
myBST.insert(10);
myBST.insert(100);
myBST.insert(320000);
myBST.insert(1);
myBST.insert(3);
log = (value) => {
console.log(value);
}
myBST.depthFirstTraversal(log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment