Created
January 26, 2019 14:05
-
-
Save bflannery/bf7ab09e78b2929a02630fa3c56091ec to your computer and use it in GitHub Desktop.
ES6 Binary Search Tree
This file contains 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
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 (!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 (!this.right) return false; | |
else return this.right.contains(value); | |
} | |
} | |
depthFirstTraversal(iteratorFunc, order) { | |
if (order === 'pre-order') iteratorFunc(this.value); | |
if (this.left) this.left.depthFirstTraversal(iteratorFunc, order) | |
if (order === 'in-order') iteratorFunc(this.value) | |
if (this.right) this.right.depthFirstTraversal(iteratorFunc, order) | |
if (order === 'post-order') iteratorFunc(this.value) | |
} | |
breadthFirstTraversal(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); | |
} | |
} | |
getMinVal() { | |
if (this.left) return this.left.getMinVal(); | |
else return this.value; | |
} | |
getMaxVal() { | |
if (this.right) return this.right.getMaxVal(); | |
else return this.value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment