Skip to content

Commit

Permalink
Create BinarySearchTree.js
Browse files Browse the repository at this point in the history
  • Loading branch information
TRIPATHISHIWANSHI authored Oct 15, 2023
1 parent 46362e3 commit 69d0aee
Showing 1 changed file with 85 additions and 0 deletions.
85 changes: 85 additions & 0 deletions Trees/BinarySearchTree.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}

class BinarySearchTree {
constructor() {
this.root = null;
}

insert(value) {
const newNode = new Node(value);

if (!this.root) {
this.root = newNode;
} else {
this.insertNode(this.root, newNode);
}
}

insertNode(node, newNode) {
if (newNode.value < node.value) {
if (node.left === null) {
node.left = newNode;
} else {
this.insertNode(node.left, newNode);
}
} else {
if (node.right === null) {
node.right = newNode;
} else {
this.insertNode(node.right, newNode);
}
}
}

search(value) {
return this.searchNode(this.root, value);
}

searchNode(node, value) {
if (node === null) {
return false;
}

if (value < node.value) {
return this.searchNode(node.left, value);
} else if (value > node.value) {
return this.searchNode(node.right, value);
} else {
return true;
}
}

inOrderTraversal(callback) {
this.inOrderTraversalNode(this.root, callback);
}

inOrderTraversalNode(node, callback) {
if (node !== null) {
this.inOrderTraversalNode(node.left, callback);
callback(node.value);
this.inOrderTraversalNode(node.right, callback);
}
}
}

// Example usage:
const bst = new BinarySearchTree();
bst.insert(10);
bst.insert(5);
bst.insert(15);
bst.insert(3);
bst.insert(7);
bst.insert(12);
bst.insert(18);

console.log("In-order traversal:");
bst.inOrderTraversal(value => console.log(value));

console.log("Search for 7:", bst.search(7)); // Should return true
console.log("Search for 9:", bst.search(9)); // Should return false

0 comments on commit 69d0aee

Please sign in to comment.