Skip to content

Instantly share code, notes, and snippets.

@fernandozamoraj
Forked from benlesh/BinaryTree.js
Created November 22, 2018 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fernandozamoraj/337c349a340433a91ed8255cefd9e227 to your computer and use it in GitHub Desktop.
Save fernandozamoraj/337c349a340433a91ed8255cefd9e227 to your computer and use it in GitHub Desktop.
A simple Binary Tree implementation in JavaScript
/**
* Binary Tree
* (c) 2014 Ben Lesh <ben@benlesh.com>
* MIT license
*/
/*
* A simple Binary Tree implementation in JavaScript
*/
function BinaryTree() {
var self = this;
var root;
function traverse(value, fn) {
var found = root,
side, parent;
while(found && found.value !== value) {
parent = found;
if(value > found.value) {
side = 'right';
found = found.right;
} else {
side = 'left';
found = found.left;
}
}
return { found: found, parent: parent, side: side };
}
self.add = function (value, item) {
if(typeof value === 'undefined') {
throw new Error('value cannot be undefined');
}
var node = new BinaryTreeNode(value, item);
if(!root) {
root = node;
return;
}
var result = traverse(value);
if(!result.found) {
result.parent[result.side] = node;
} else {
throw new Error('two items of the same value added');
}
};
self.search = function(value) {
var result = traverse(value);
return result.found ? result.found.item : null;
};
self.contains = function(value) {
return !!self.find(value)
};
self.root = function (){
return root;
};
function BinaryTreeNode(value, item) {
this.value = value;
this.item = item;
this.left = null;
this.right = null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment