Last active
January 18, 2019 06:47
-
-
Save IAMIronmanSam/15bf3180f442067fe9e08d592b01f223 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Tree = function(data) { | |
this.data = data; | |
this.left = null; | |
this.right = null; | |
} | |
Tree.prototype.insert = function(value){ | |
if(value <= this.data){ | |
if(this.left == null){ | |
this.left = new Tree(value); | |
} else{ | |
this.left.insert(value); | |
} | |
} else{ | |
if(this.right == null){ | |
this.right = new Tree(value); | |
} else { | |
this.right.insert(value); | |
} | |
} | |
}; | |
Tree.prototype.search = function(value){ | |
if(value == this.data){ | |
return true; | |
} else if(value < this.data){ | |
if(this.left == null){ | |
return false; | |
} else { | |
return this.left.search(value); | |
} | |
} else { | |
if(this.right == null){ | |
return false; | |
} else { | |
return this.right.search(value); | |
} | |
} | |
}; | |
Tree.prototype.remove = function(tree,value){ | |
if(tree.data == null){ | |
return null; | |
} else if(value < tree.data){ | |
tree.left = tree.left.remove(tree.left,value); | |
return tree; | |
} else if(value > tree.data){ | |
tree.right = tree.right.remove(tree.right,value); | |
return tree; | |
} else { | |
if(tree.left === null && tree.right === null) | |
{ | |
tree = null; | |
return tree; | |
} | |
if(tree.left === null) | |
{ | |
tree = tree.right; | |
return tree; | |
} | |
else if(tree.right === null) | |
{ | |
tree = tree.left; | |
return tree; | |
} | |
} | |
}; | |
var BinarySearchTree = new Tree(10); | |
BinarySearchTree.insert(11); | |
BinarySearchTree.insert(8); | |
BinarySearchTree.insert(6); | |
BinarySearchTree.insert(7); | |
BinarySearchTree.insert(5); | |
console.log(BinarySearchTree); | |
var isConatins = BinarySearchTree.search(5); | |
console.log(isConatins); | |
var newtree = BinarySearchTree.remove(BinarySearchTree,5); | |
console.log(newtree); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment