JS - Binary tree - basic example
JavaScript
// Based on reference material written by Nicholas C. Zakas
// https://www.nczonline.net/blog/2009/06/09/computer-science-in-javascript-binary-search-tree-part-1/
console.clear();
function BinarySearchTree() {
this._root = null;
}
BinarySearchTree.prototype = {
// restore constructor
constructor: BinarySearchTree,
add: function(value) {
// create a new item object, and place data in it
var node = {
value: value,
left: null,
right: null
},
// used to traverse the structure
current;
// special case: no items in the tree yet
if (this._root === null) {
this._root = node;
} else {
current = this._root;
while (true) {
// if the new value is less than this node's value, go left
if (value < current.value) {
// if there's no left, then the new node belongs there
if (current.left === null) {
current.left = node;
break;
} else {
current = current.left;
}
}
// if the new value is great than this node's value, to right
else if (value > current.value) {
// if there's no right, then the new node belongs there
if (current.right === null) {
current.right = node;
break;
} else {
current = current.right;
}
}
// if the new value is equal to the current one, just ignore it
else {
break;
}
}
}
},
contains: function(value) {
var found = false,
current = this._root;
// make sure there is a...