Skip to content

Instantly share code, notes, and snippets.

@jialinhuang00
Last active December 19, 2017 15:03
Show Gist options
  • Save jialinhuang00/42ab8a320c24e7d8c4493bf593859d1b to your computer and use it in GitHub Desktop.
Save jialinhuang00/42ab8a320c24e7d8c4493bf593859d1b to your computer and use it in GitHub Desktop.
/*-----------------------------------------------------------------------------
the reference is from UdemyCourse: LearningDataStructuresinJavascriptFromScratch
-----------------------------------------------------------------------------*/
function BST(value) {
this.value = value;
this.left = null;
this.right = null;
}
BTS.prototype.insert = function(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);
}
}
};
BST.prototype.contains = function(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);
}
};
BST.prototype.depthFirstTraversal = function(iteratorFunc, order){
// root left right
if(order === 'pre-order') iteratorFunc(this.function);
if(this.left) this.left.depthFirstTraversal(iteratorFunc, order);
// left root right
if(order === "in-order") iteratorFunc(this.value);
if(this.right) this.right.depthFirstTraversal(iteratorFunc, order);
// left right root
if(order === 'post-order') iteratorFunc(this.value);
};
BST.prototype.BreadthFirstTraversal = function(iteratorFunc) {
var queue = [this];
while (queue.length) {
var treeNode = queue.shift();
iteratorFunc(treeNode);
if(treeNode.left) queue.push(treeNode.left);
if(treeNode.right) queue.push(treeNode.right);
}
};
function log(value) {
console.log(value);
}
BST.prototype.getMinVal = function () {
if(this.left) return this.left.getMinVal();
else return this.value;
};
BST.prototype.getMaxVal = function () {
if(this.right) return this.right.getMaxVal();
else return this.value;
};
var bst = new BST(2);
bst.insert(31);
bst.insert(311);
bst.insert(21);
bst.insert(45);
bst.insert(98);
bst.insert(1);
bst.depthFirstTraversal(log, 'post-order');
@jialinhuang00
Copy link
Author

@jialinhuang00
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment