class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BST {
constructor() {
this.root = null;
}
insert(value) {
const newNode = new Node(value);
if (!this.root) {
this.root = newNode;
return;
}
let curr = this.root;
while (true) {
if (value < curr.value) {
if (!curr.left) {
curr.left = newNode;
return;
}
curr = curr.left; // move left
} else {
if (!curr.right) {
curr.right = newNode;
return;
}
curr = curr.right; // move right
}
}
}
search(value) {
let curr = this.root;
while (curr) {
if (value === curr.value) {
return true; // found
} else if (value < curr.value) {
curr = curr.left; // go left
} else {
curr = curr.right; // go right
}
}
return false; // not found
}
}
// Driver code
const bst = new BST();
[10, 5, 15, 3, 7, 20].forEach(v => bst.insert(v));
const found = bst.search(7);
console.log(found ? 'Found 7' : '7 not found');start searching from root node
if (value === curr.value) { return true; }
check if current node is the target
else if (value < curr.value) { curr = curr.left; }
go left if target is smaller
else { curr = curr.right; }
go right if target is bigger