Created
November 6, 2016 04:29
-
-
Save ZaynahGiti/0f526515d2414862653f40204be836ec to your computer and use it in GitHub Desktop.
Binary Search Tree created by ZaynahGiti - https://repl.it/EPbx/4
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
| function BST(value) { | |
| this.value = value; | |
| this.right = null; | |
| this.left = null; | |
| } | |
| BST.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 (this.value === value) return true; | |
| 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.depthFirstForEach = function(iteratorFunc, order) { | |
| if (order === 'pre-order') iteratorFunc(this.value); | |
| if (this.left) this.left.depthFirstForEach(iteratorFunc, order); | |
| if (order === 'in-order') iteratorFunc(this.value); | |
| if (this.right) this.right.depthFirstForEach(iteratorFunc, order); | |
| 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); | |
| } | |
| }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

Binary Search Tree Source Code