Binary Search Trees

Algorithms · Advanced Placement

Binary Search Trees: the big picture

A binary search tree stores keys so that every node's left subtree contains only smaller keys and its right subtree only larger ones, which makes an in-order traversal produce the keys in sorted order and makes searching a matter of descending from the root comparing at each step. Search, minimum, maximum, predecessor, successor, insertion and deletion all take time proportional to the height of the tree, so the tree's shape determines performance entirely. A randomly built tree has expected logarithmic height, but inserting sorted keys produces a path of linear height, which reduces the tree to a linked list and every operation to linear time. Deletion is the only structurally awkward operation, with three cases according to the number of children, the hardest replacing the node with its in-order successor. Augmenting a tree with subtree sizes allows the element of a given rank to be found and a key's rank to be computed in time proportional to the height, which an ordinary tree cannot do. Interval trees augment with subtree maxima to find overlapping intervals efficiently. The general method for augmentation requires that the extra information at a node be computable from the node and its children alone, so that it can be maintained through rotations.

Binary Search Trees, Traversal & the Shape Problem

A binary search tree keeps everything smaller on the left and everything larger on the right, which makes in-order traversal produce sorted output and makes search a descent from the root. Every operation costs time proportional to the height, so shape is everything. A randomly built tree has expected logarithmic height, which is fine — but insert sorted keys and you get a path of linear height, turning the tree into a linked list. Since sorted insertion is extremely common in practice, this is not a theoretical worry.

{{illustration:algos-l10-f1}}

{{illustration:algos-l10-f2}}

Key relations

- The search tree invariant and its cost. left(x) < x < right(x) ; T_search = O(h) ; E[h_random] ≈ 4.31log₂ n

Balanced Trees, Rotations & Augmentation

Balanced trees keep the height logarithmic by rebalancing after each update, and the mechanism is the rotation — a local restructuring that changes shape while preserving the ordering invariant. Red-black trees enforce a colouring that bounds the height at twice the logarithm; AVL trees enforce a stricter height condition and so stay shorter but rebalance more. Augmenting a tree with extra per-node data works provided that data is computable from the node and its children, which is exactly what lets it survive rotations.

{{illustration:algos-l10-f3}}

{{illustration:algos-l10-f4}}

Key relations

- Height bounds and the augmentation condition. h_RB ≤ 2log₂(n+1) ; size(x) = size(left) + size(right) + 1