Last active
December 19, 2017 15:03
-
-
Save jialinhuang00/42ab8a320c24e7d8c4493bf593859d1b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*----------------------------------------------------------------------------- | |
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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pseudo code here
https://medium.freecodecamp.org/deep-dive-into-graph-traversals-227a90c6a261