Created
May 1, 2020 19:51
-
-
Save purnimagupta/344edb0cc3973d84ba8d86b3a6b4e465 to your computer and use it in GitHub Desktop.
Binary Search Tree in JavaScript
This file contains hidden or 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
class Node { | |
constructor(val) { | |
this.val = val; | |
this.left = null; | |
this.right = null; | |
} | |
insert(val) { | |
if(val < this.val && !this.left) { | |
// create a new node at the left of the tree | |
this.left = new Node(val); | |
} | |
else if(val < this.val && this.left) { | |
this.left.insert(val) | |
} | |
else if(val > this.val && !this.right) { | |
this.right = new Node(val) | |
} | |
else if(val > this.val && this.right) { | |
this.right.insert(val) | |
} | |
} | |
search(givenEle){ | |
if(this.val === givenEle) { | |
return true | |
} else if(this.val > givenEle && this.left){ | |
return this.left.search(givenEle) | |
} else if(this.val < givenEle && this.right) { | |
return this.right.search(givenEle) | |
} | |
return false | |
} | |
} | |
// create a bst with 3 nodes. (Root node contains the value 10) | |
let bst = new Node(10); | |
bst.insert(9) | |
bst.insert(6) | |
console.log(bst) | |
console.log(bst.search(9)) // prints true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment