Skip to content

Instantly share code, notes, and snippets.

Created March 10, 2017 18:27
Show Gist options
  • Save anonymous/ce4e40e9d9e4af27d66690dcc16245a3 to your computer and use it in GitHub Desktop.
Save anonymous/ce4e40e9d9e4af27d66690dcc16245a3 to your computer and use it in GitHub Desktop.
function Node(interval){
this.interval = interval;
this.value = interval[0];
this.max = interval[1];
this.left = null;
this.right = null;
}
function BinarySearchTree(){
this.root = null;
}
BinarySearchTree.prototype.push = function(interval){
var root = this.root;
//If root is null, node = root
if(!root){
this.root = new Node(interval);
this.root.max = this.root.interval[1];
return;
}
var currentNode = root;
var newNode = new Node(interval);
while(currentNode){
if(interval[0] < currentNode.value){
//If currentNode.left is null, replace with new node
if(!currentNode.left){
if (newNode.max > currentNode.max){
currentNode.max = newNode.max;
}
currentNode.left = newNode;
break;
}
//Else, move left
else{
if (newNode.max > currentNode.max){
currentNode.max = newNode.max;
}
currentNode = currentNode.left;
}
}
else{
//If currentNode.right is null, replace with new node
if(!currentNode.right){
if (newNode.max > currentNode.max){
currentNode.max = newNode.max;
}
currentNode.right = newNode;
break;
}
//Else, move right
else{
if (newNode.max > currentNode.max){
currentNode.max = newNode.max;
}
currentNode = currentNode.right;
}
}
}
}
var bst = new BinarySearchTree();
bst.push([17, 19]);
bst.push([21, 24]);
bst.push([5, 8]);
bst.push([4, 8]);
bst.push([15, 18]);
bst.push([7, 10]);
bst.push([16, 22]);
console.log(bst);
function checkIntersection(interval, tree){
var currentNode = tree.root;
while (currentNode){
if (interval[0] <= currentNode.interval[1] && currentNode.interval[0] <= interval[1]){
console.log("INTERSECTION: "+interval, currentNode.interval);
}
if (!currentNode.left){
console.log("NO NODE TO LEFT, GO RIGHT");
if (!currentNode.right){
console.log("NO MORE NODES");
break
}
currentNode = currentNode.right;
}
if (currentNode.left.max < interval[0]){
console.log("LEFT MAX: "+currentNode.left.max+" < "+interval[0]+" GO RIGHT");
currentNode = currentNode.right;
}
else {
console.log("INTERVAL MAY BE TO LEFT, GO LEFT");
currentNode = currentNode.left;
}
}
}
checkIntersection([6,8], bst);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment