Card 09/ 09

RecapDifficulty: Advanced2 min

Recap: Binary Search Trees

Bounds, not children; shape from insertion order; the successor for deletion; balance for guarantees.

Binary search trees come down to the seven ideas below, each listed with the card that covers it. Most of them follow from one rule, the ordering of whole subtrees, and from the fact that every operation walks a single path from the root.

What the topic established, and which card it was on
The ideaWhere
Every key in a node's left subtree is smaller and every key in its right subtree larger, so a search follows one pathBinary Search Trees: Ordered for One Descent
A search and an insert take the same path, and a new key always becomes a leaf; duplicates need a stated ruleSearch and Insert in One Descent
Validity needs a lower and an upper bound carried down from the ancestors, not a comparison with the childrenChecking Only Each Node's Children
Insertion order decides the height, from about log n up to n - 1 when keys arrive sortedInsertion Order Decides a Tree's Shape
A node with two children takes its in-order successor's key, and the successor is deleted from the right subtreeDelete a Node With Two Children
Every operation is O(h); Java's TreeMap is a red-black tree that keeps h at O(log n)Binary Search Tree in Python, Java and TypeScript
A balanced tree is the one structure of the three that changes cheaply and answers ordered questions cheaplyBinary Search Tree vs Sorted Array and Hash Table

Deletion is the operation with the most to remember, and its three cases differ only in how many children the node has. The second table sets them side by side. Only the last case touches two nodes, and both lie on one path down from the root, so every case costs O(h) on a tree of height h.

The three cases of deleting a key from a binary search tree
The node hasWhat happensWhy the order holds
No childrenIt is removed and its parent's link becomes emptyNothing else moves
One childThe child moves up into its placeThe child's subtree was already on the correct side of the parent
Two childrenIts key is replaced by the successor's, and the successor is deletedThe successor is the next key in sorted order, and it has no left child

Together they let you search, insert into and delete from a binary search tree by hand, check whether a tree is valid, predict its height from the order its keys arrived, and decide when a balanced tree beats a hash table or a sorted array.