Created
April 2, 2020 05:07
-
-
Save JustAyush/0634d5324d0eab4372f7338018f28538 to your computer and use it in GitHub Desktop.
Binary Search Tree Implementation 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
// Try edit message | |
class Node { | |
constructor(value) { | |
this.value = value; | |
this.leftNode = null; | |
this.rightNode = null; | |
} | |
addNode(newNode) { | |
if(newNode.value < this.value) { | |
if(this.leftNode == null) this.leftNode = newNode; | |
else this.leftNode.addNode(newNode); | |
} else if(newNode.value > this.value) { | |
if(this.rightNode == null) this.rightNode = newNode; | |
else this.rightNode.addNode(newNode); | |
} | |
} | |
// for In-Order, Pre-Order and Post-Order Traversal | |
visitInOrder() { | |
if(this.leftNode != null) | |
this.leftNode.visitInOrder(); | |
console.log(this.value); | |
if(this.rightNode != null) | |
this.rightNode.visitInOrder(); | |
} | |
visitPreOrder() { | |
console.log(this.value); | |
if(this.leftNode != null) | |
this.leftNode.visitPreOrder(); | |
if(this.rightNode != null) | |
this.rightNode.visitPreOrder(); | |
} | |
visitPostOrder() { | |
if(this.leftNode != null) | |
this.leftNode.visitPostOrder(); | |
if(this.rightNode != null) | |
this.rightNode.visitPostOrder(); | |
console.log(this.value); | |
} | |
search(value) { | |
if(value < this.value) { | |
if(this.leftNode == null) console.log("Not Found"); | |
else this.leftNode.search(value); | |
} else if(value > this.value) { | |
if(this.rightNode == null) console.log("Not Found"); | |
else this.rightNode.search(value); | |
} else { | |
console.log('Found') | |
} | |
} | |
} | |
class Tree { | |
constructor() { | |
this.root = null; | |
this.oldValue; | |
this.newValue; | |
} | |
addValue(value) { | |
let newNode = new Node(value); | |
if(this.root == null) { | |
this.root = newNode; | |
} else { | |
this.root.addNode(newNode); | |
} | |
} | |
inOrderTraverse() { | |
this.root.visitInOrder(); | |
} | |
preOrderTraverse() { | |
this.root.visitPreOrder(); | |
} | |
postOrderTraverse() { | |
this.root.visitPostOrder(); | |
} | |
searchValue(value) { | |
this.root.search(value); | |
} | |
print() { | |
console.log(this.root); | |
} | |
} | |
let t = new Tree(); | |
t.addValue(50); | |
t.addValue(20); | |
t.addValue(80); | |
t.addValue(10); | |
t.addValue(30); | |
t.addValue(70); | |
t.addValue(90); | |
t.print(); | |
console.log("In-Order Traversal"); | |
t.inOrderTraverse(); | |
console.log("Pre-Order Traversal"); | |
t.preOrderTraverse(); | |
console.log("Post-Order Traversal"); | |
t.postOrderTraverse(); | |
t.searchValue(50); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment