Skip to content

Instantly share code, notes, and snippets.

@ZaynahGiti
Created November 6, 2016 04:29
Show Gist options
  • Select an option

  • Save ZaynahGiti/0f526515d2414862653f40204be836ec to your computer and use it in GitHub Desktop.

Select an option

Save ZaynahGiti/0f526515d2414862653f40204be836ec to your computer and use it in GitHub Desktop.
Binary Search Tree created by ZaynahGiti - https://repl.it/EPbx/4
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);
}
};
@ZaynahGiti
Copy link
Author

Binary Search Tree Source Code

@ZaynahGiti
Copy link
Author

screen shot 2016-11-06 at 5 49 14 am

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