Binary Search Trees
Aashish Panchal
Posted on October 21, 2020
/*
Example For Binary Search Tree
__10__
/ \
5 13
/ \ / \
2 7 11 16
/\ \ \
1 3 9 18
*/
class Node {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor(){
this.root = null;
}
// Insert a New value in tree
insert(value) {
var newNode = new Node(value);
if(this.root === null) {
this.root = newNode;
return this;
} else {
var current = this.root;
while(true) {
if(value < current.value) {
if(current.left === null) {
current.left = newNode;
console.log(` -> ${current.value} left value -> ${value} added `)
return this;
} else {
current = current.left;
}
} else if(value > current.value) {
if (current.right === null) {
current.right = newNode;
console.log(` -> ${current.value} right value -> ${value} added `)
return this;
} else {
current = current.right;
}
}
if(current.value == value) {
console.log(` -> ${value} is Duplicate value Please Enter Unique Value `)
return;
}
}
}
}
// find The Value in tree
find(value) {
if(this.root === null) return false;
var current = this.root,
found = false;
while(current && !found) {
if(value < current.value) {
current = current.left;
} else if (value > current.value) {
current = current.right;
} else {
console.log(`Founded Successfully -> ${value}`);
return current;
}
}
if(!found) console.log(`Not Founded -> ${value}`);
return current;
}
// Same as on find
contains(value) {
if(this.root === null) return false;
var current = this.root,
found = false;
while(current && !found) {
if(value < current.value) {
current = current.left;
} else if (value > current.value) {
current = current.right;
} else {
console.log(`Founded Successfully -> ${value}`);
return current;
}
}
if(!found) console.log(`Not Founded -> ${value}`);
return current;
}
}
var tree = new BinarySearchTree();
tree.insert(10)
tree.insert(5)
tree.insert(13)
tree.insert(2)
tree.insert(7)
tree.insert(11)
tree.insert(16)
💖 💪 🙅 🚩
Aashish Panchal
Posted on October 21, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
opensource RoSctober Fest Wrap-Up: A Month of Code, Community, and Sloth Points! 🦥
November 13, 2024
hacktoberfest ✨ From Contributor to Core Project Maintainer: My Open Source Journey ✨
October 11, 2024
hacktoberfestchallenge My Hacktoberfest 2024 Journey: A Month of Code, Growth, and Unforgettable Lessons 🚀
November 1, 2024