Trees
BST Search
Search a binary search tree for one present and one absent value.
Algorithm
Basic Implementation
basic.js
class Node {
constructor(value, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
function render(node) {
if (node === null) return "_";
if (node.left === null && node.right === null) return String(node.value);
return `${node.value}(${render(node.left)},${render(node.right)})`;
}
function sampleTree() {
return new Node(4, new Node(2, new Node(1), new Node(3)), new Node(6, new Node(5), new Node(7)));
}
const root = sampleTree();
function search(root, target) { let node = root; while (node !== null) { if (target === node.value) return true; node = target < node.value ? node.left : node.right; } return false; }
console.log(search(root, 5) ? "5 found" : "5 not found");
console.log(search(root, 8) ? "8 found" : "8 not found");
Complexity
- Time: O(h) per search
- Space: O(1) iterative
Implementation notes
- The searched tree is built from JavaScript
Nodeobjects withvalue,left, andrightproperties. Missing children arenull, and the search reads existing references without allocating or mutating nodes. search(root, target)is iterative:let node = rootholds the current cursor, andwhile (node !== null)stops when a missing child is reached.- Comparisons use
Numbersemantics.target === node.valuereturnstrue; otherwisetarget < node.value ? node.left : node.rightchooses the next reference, so smaller targets move left and larger targets move right. - The replay searches
5through cursors4 -> right,6 -> left, then5 -> match. It searches missing8through4 -> right,6 -> right,7 -> right, then reachesnulland returnsfalse. - The two
console.logcalls format booleans into5 foundand8 not found, producing stdout5 found\n8 not found. The material heap allocation is the seven-node sample tree; the search itself only updates the cursor binding.
search path
A comparison chooses one subtree at each step, so whole branches are skipped.