function BinarySearchTree(){
var _root = null;
Object.defineProperty(this, '_root'){
get: function(){
return _root;
}
};
Object.defineProperty(this, 'contents'){
};
Object.defineProperty(this, 'size'){
};
}
BinarySearchTree.prototype = {
contains: function(value){
var found = false,
current = this._root;
while(!found && current){
//if less than current node, go left.
if(value < current.value){
current = current.left;
//if greater than current node, go right.
} else if (value < current.value){
current = current.right;
//values are equal, found it!
} else {
found = true;
}
//proceed when found
return found;
}
},
add: function(value){
//create a new node instance
var node = {
value: value,
left: null,
right: null
},
//Used to traverse tree structure
current;
//Param root if tree is empty.
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;
}
} 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;
}
}
}
},
traverse: function(process){
//helper function
function inOrder(node){
if (node){
//traverse the left subree
if(node.left !== null){
inOrder(node.left);
}
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.