A binary search tree imposes one invariant everywhere: for EVERY node, all values in its left subtree are smaller, and all values in its right subtree are larger. That local rule creates global order, which lets you binary-search the tree. At each node, one comparison tells you which subtree can hold the target; the other is discarded entirely, exactly like discarding half an array.
Search, insert, and delete all follow the same path shape: walk from the root, one comparison per level. Cost = height + 1. For a balanced tree that's O(log n). But the invariant says nothing about BALANCE, insert sorted data 1,2,3,4,5 into a naive BST and you get a linked list in disguise, O(n) for everything. Self-balancing trees (AVL, red-black) add rotation rules that keep height ≈ log n; they power Java's TreeMap and the C++ std::map.
Search and insert
class BSTNode {
constructor(value) { this.value = value; this.left = null; this.right = null; }
}
function insert(root, value) {
if (!root) return new BSTNode(value); // found the empty slot
if (value < root.value) root.left = insert(root.left, value);
else if (value > root.value) root.right = insert(root.right, value);
return root; // equal → ignore (set semantics)
}
function search(root, value) {
let cur = root;
while (cur) {
if (value === cur.value) return true;
cur = value < cur.value ? cur.left : cur.right; // discard one subtree
}
return false;
}
// In-order traversal of a BST yields values in SORTED order,
// the invariant's most elegant consequence:
function sortedValues(root, out = []) {
if (!root) return out;
sortedValues(root.left, out);
out.push(root.value);
sortedValues(root.right, out);
return out;
}| Operation / case | Cost | Notes |
|---|---|---|
| Search / insert / delete (balanced) | O(log n) | height ≈ log₂ n |
| Search / insert / delete (degenerate) | O(n) | sorted insertion order |
| In-order traversal | O(n) | returns sorted sequence |
| Range queries | O(log n + k) | k = results, where BSTs beat hash tables |