-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst.js
81 lines (70 loc) · 1.83 KB
/
bst.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Define a Node class to represent each node in the binary search tree
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// Define the Binary Search Tree class
class BinarySearchTree {
constructor() {
this.root = null;
}
// Method to insert a new node into the BST
insert(value) {
const newNode = new Node(value);
if (this.root === null) {
this.root = newNode;
} else {
this.insertNode(this.root, newNode);
}
}
//helper function
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);
}
}
}
// Method to perform binary search
search(target) {
return this.searchNode(this.root, target);
}
searchNode(node, target) {
if (node === null || node.value === target) {
return node;
}
if (target < node.value) {
return this.searchNode(node.left, target);
} else {
return this.searchNode(node.right, target);
}
}
}
// Example usage:
const bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(8);
bst.insert(1);
bst.insert(4);
bst.insert(7);
bst.insert(9);
const targetValue = 7;
const result = bst.search(targetValue);
console.log(bst)
if (result) {
console.log(`Found ${targetValue} in the BST.`);
} else {
console.log(`${targetValue} not found in the BST.`);
}