Binary search tree
Based on some of Nicholas Zakas' work and other implementations of the typical BST data structure. Source: http://www.nczonline.net/blog/2009/06/16/computer-science-in-javascript-binary-search-tree-part-2/
by b_long
JavaScript
$(document).ready(function () {
console.log("BST playground starting up...");
var nonNull = function (ref) {
if (typeof ref === "undefined" || ref === null) {
return false;
}
return true;
};
function Node(key, name) {
if (nonNull(key) && nonNull(name)) {
this.key = key;
this.name = name;
// Children always null at construction
this.leftChild = null;
this.rightChild = null;
} else {
throw new Error("An error occurred constructing a new node!");
}
}
Node.prototype.toString = function () {
return "This Node (" + this.name + ") has key: '" + this.key + "'";
};
Node.prototype.getParent = function () {
return this.parentNode;
};
Node.prototype.printInTree = function(){
//http://stackoverflow.com/a/8948691/320399
}
function BTree() {
this.root = null;
}
BTree.prototype.addNode = function (key, name) {
var newNode = new Node(key, name);
//console.log("Attempting to insert new node: " + newNode);
if (this.root === null) {
console.log("There is no root node, setting new node as root");
this.root = newNode;
} else {
//console.log("A root node exists, finding appropriate parent node");
// Start with the root node and traverse
// until we find the appropriate parent node
// Root is the top-most parent, so start there
var inserted = false,
// Used to traverse
current = this.root;
do {
// Check if the new node should be set as a
// left or right child (based on it's key)
if (key < current.key) {
// Switch focus to the left child
// so long as it has a left child
if (current.leftChild === null)...