Insert 31 keys in sorted order and the tree is a chain of height 30. Insert the middle key first and the height is 4. Every operation costs the height, so the order of arrival decides the speed.
Pick an insertion order and drag the number of keys. Watch where the height lands on the ruler. Then we build, piece by piece, the rule that orders the tree, search, successor, insert, delete, the four walks and why height is everything.
You need a little Python and the idea of a pointer (a field that refers to another object). We build the rest from zero.
Based on Chapter 12, Binary Search Trees, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Hash Tables. Next: Red-Black Trees.
Illustrative: the keys are 1 to n. Height counts the edges on the longest path from the root down. Random draws a fresh order on each press of New shuffle.
Chapter 0
See a sorted array and a linked list each fail at half the job, and meet the structure that does both
You keep 10,000 contacts in sorted order. People add names, look them up and delete them all day. Which structure holds them?
A sorted array finds a name by binary search: at most 14 probes for 10,000 names. But a new name must squeeze in, so every name after it shifts one slot. In the worst case that is 10,000 moves.
A linked list is a chain of nodes joined by pointers. Once you know the spot, an insert is two pointer writes. But you cannot jump to the middle of a list. Finding the spot means a walk from the head: up to 10,000 steps.
Each bar is the worst-case number of steps for one operation. The axis is logarithmic. Drag the size and switch between search and insert.
Worst-case counts. Array search: ⌊log₂n⌋ + 1 probes; array insert adds n moves. List: n steps to reach the spot. Balanced tree: ⌊log₂n⌋ + 1 comparisons, plus one link for an insert.
With n = 10,000 the array searches in 14 probes but pays 14 + 10,000 = 10,014 steps to insert. The list pays about 10,000 for either job. A balanced tree pays 14 to search and 15 to insert.
That tree is a binary search tree (BST): each key sits in a node with a left and a right child pointer. Search goes left or right at each node, like binary search. Insert hangs one new leaf, like a list insert. Both cost the height h of the tree: the number of edges on its longest path from the top node down.
The failure. Symptom: an index that was fast in testing crawls once the data grows. Measure: time 1,000 inserts at n, 2n and 4n; if the time doubles each step, an operation is linear. Fix: use a structure whose operations cost the height, and keep the height small.
Chapter 1
Put smaller keys left and larger keys right, and check the rule against whole subtrees
Write seven keys on cards: 2, 5, 7, 10, 12, 15, 20. Put 10 at the top. Put every smaller card below it on the left and every larger card below it on the right. Repeat inside each side. You have built a binary search tree.
Each node holds a key and three pointers: left, right and parent. A node with no children is a leaf. The node with no parent is the root. Everything below a node on one side is its left or right subtree.
One rule makes it a search tree. Take any node x. Call any node in its left subtree y, and any node in its right subtree z, at any depth.
y-dot-key is at most x-dot-key, which is at most z-dot-key.
Pick a node x. Every key anywhere below it on the left must be no larger than x.key. Every key anywhere below it on the right must be no smaller. Do this for every node, not only against its two children.
At x = 10 the left keys are 2, 5, 7 and the right keys are 12, 15, 20. Each of 2, 5, 7 is at most 10, and 10 is at most each of 12, 15, 20. At x = 5: 2 ≤ 5 ≤ 7. The rule holds at both.
Pick a node. Blue is its left subtree, pink its right. Then plant 17 where 7 sits and check node 5, then node 10.
The tree is the chapter's seven-key example. The 17 is a planted mistake.
With 17 planted, node 5 still passes: 17 is larger than 5 and sits on its right. Node 10 fails: 17 lies in its left subtree but is larger than 10. A search for 17 turns right at 10 and never finds it.
The node in Python is four fields. CLRS keeps the parent pointer because successor and delete climb upward.
pythonclass Node: def __init__(self, key): self.key = key # the value stored here self.left = None # subtree of smaller keys self.right = None # subtree of larger keys self.parent = None # the node above, None at the root
The failure. Symptom: a search misses a key that a printout of the tree shows. Measure: run the in-order walk of Chapter 6; if its output is not sorted, the rule is broken. Fix: find the first out-of-order pair; one of its keys sits in the wrong subtree.
Chapter 2
Walk one path down from the root and count what it costs
Look for 13 in the seven-key tree. Start at the root, 10. 13 is larger, so go right to 15. 13 is smaller, so go left to 12.
13 is larger than 12, so go right, and there is no node there. 13 is not in the tree. That took three comparisons.
Each comparison rules out a whole subtree. The search walks one path from the root down and never comes back up. The minimum is at the end of the all-left path; the maximum is at the end of the all-right path.
Pick a key and press Search. Warm nodes are the comparisons, in order. Try a key that is missing.
The seven-key tree from Chapter 1.
How many comparisons does a search cost? Call the depth of a node d: the number of edges from the root down to it. Call the height of the tree h, the depth of its deepest node. Call the number of comparisons c.
c equals d plus one, which is at most h plus one.
Count the edges from the root to the node where the search stops. Add one for the root. That is c. No node is deeper than h, so no search makes more than h + 1 comparisons.
The search for 13 stops at 12, at depth d = 2, so c = 2 + 1 = 3. This tree has h = 2, so every search costs at most 3. The same seven keys in a chain have h = 6, and a search can cost 7.
pythondef search(x, k): while x is not None and k != x.key: x = x.left if k < x.key else x.right # rule out one subtree return x # the node, or None for a miss def minimum(x): while x.left is not None: x = x.left return x def maximum(x): while x.right is not None: x = x.right return x
The failure. Symptom: a recursive search raises RecursionError on a large tree. Measure: print the height; Python's default recursion limit is 1,000 calls, and a chain of 5,000 keys has height 4,999. Fix: use the loop above. It needs no stack.
Chapter 3
Find the next key in sorted order with no sort, using the shape of the tree
Your contact app shows one name, and you swipe to the next. Which node holds the next name? The successor of node x is the node with the smallest key larger than x.key. The predecessor is the node with the largest key smaller than x.key.
The shape of the tree tells you where to look. There are two cases.
Pick a node, then press Find successor. Warm is the walk; purple is the answer. Compare 10 with 13.
The seven-key tree plus 13, inserted as the right child of 12.
The successor of 10: it has a right subtree at 15, so go left to 12, which has no left child. The answer is 12 (case 1).
The successor of 13: it has no right subtree. 13 is the right child of 12, so climb on. 12 is the left child of 15, so stop. The answer is 15 (case 2).
Why case 2 works: every ancestor you leave from its right side is smaller than x. The first ancestor you leave from its left side is larger, and no key lies between them.
pythondef successor(x): if x.right is not None: return minimum(x.right) # case 1 y = x.parent while y is not None and x is y.right: x, y = y, y.parent # case 2: climb while x is a right child return y # None if x was the maximum
Each walk goes down one path or up one path, so successor costs O(h). The predecessor is the mirror: the maximum of the left subtree, or climb until you leave a right child.
The failure. Symptom: the "next" button skips names or bounces between two. Measure: start at the minimum, call successor n − 1 times, and compare with the sorted keys. Fix: case 1 must return the minimum of the right subtree, not the right child.
Chapter 4
Search for the key, and hang a new leaf where the search falls off
To insert a key, search for it. The search falls off the tree at an empty child pointer. Put the new node there. A new key always becomes a leaf, and no existing node moves.
The CLRS procedure walks down with two pointers. x is the current node. y is the trailing parent, one step behind x. When x becomes empty, y is the node that gets the new child.
Pick a key and press Insert. Warm is the path; green is the new leaf. Insert 21, 22, 23 in a row and watch a chain start.
Starts from the seven-key tree. The device refuses a key that is already in the tree, because this page keeps keys distinct.
Insert 13 into the seven-key tree. 13 > 10, go right. 13 < 15, go left. 13 > 12, go right: empty. 13 becomes the right child of 12, at depth 3. That is three comparisons, and the height grows from 2 to 3.
pythondef insert(tree, z): # z: a new Node with z.key set y, x = None, tree.root while x is not None: # walk down like a search y = x x = x.left if z.key < x.key else x.right z.parent = y if y is None: tree.root = z # the tree was empty elif z.key < y.key: y.left = z else: y.right = z
The order of arrival fixes the shape. Insert 3, 1, 5, 2, 4. 3 is the root; 1 goes left and 5 goes right. 2 hangs right of 1, and 4 hangs left of 5. Height 2. Insert 1, 2, 3, 4, 5: every key goes right of the last. A chain of height 4.
The failure. Symptom: inserts slow down when keys arrive in time order, such as timestamps or auto-increment IDs. Measure: print the height after each batch; if it equals n − 1, the keys arrived sorted. Fix: use a self-balancing tree (Chapter 9), or shuffle a batch before a bulk load.
Chapter 5
Remove a node in one of three cases, and lift the successor in when both children stay
Delete is the hardest operation. The node you remove may have children, and they need a new parent without breaking the BST property. Call the node to delete z. The case depends on how many children z has.
| Case | z has | What to do |
|---|---|---|
| 1 | no children | Remove z. Its parent's pointer becomes empty. |
| 2 | one child | Lift the child into z's place. |
| 3 | two children | Find y, the successor of z. Move y into z's place. |
Why the successor? y is larger than every key on z's left. It is smaller than every other key on z's right. So it can sit where z sat. And y has no left child, or that child would be the minimum instead. So lifting y out is case 1 or case 2.
CLRS builds delete from one helper. transplant(u, v) puts the subtree rooted at v in the place of the subtree rooted at u. It also fixes the parent's pointer.
Pick a node and press Delete. Purple marks the node that moves into the gap. Delete 10 and watch 13 move up first.
The seven-key tree plus 13. Each node keeps its sorted position across the page, so you see which nodes change depth.
Delete 10, which has two children. Its successor y is 12, the minimum of the right subtree. y is not a child of 10. So first transplant 13, the right child of 12, into 12's place under 15. Then 12 takes 10's place, with 5 as its left child and 15 as its right. The in-order walk still reads 2, 5, 7, 12, 13, 15, 20.
pythondef transplant(tree, u, v): if u.parent is None: tree.root = v elif u is u.parent.left: u.parent.left = v else: u.parent.right = v if v is not None: v.parent = u.parent def delete(tree, z): if z.left is None: transplant(tree, z, z.right) # case 1 or 2 elif z.right is None: transplant(tree, z, z.left) # case 2 else: # case 3 y = minimum(z.right) if y.parent is not z: # y is deeper: lift its right child first transplant(tree, y, y.right) y.right = z.right; y.right.parent = y transplant(tree, z, y) y.left = z.left; y.left.parent = y
The failure. Symptom: after a delete, successor loops or a subtree vanishes. Measure: check that c.parent is p for every child c of every node p, and that the in-order walk comes out sorted. Fix: set v.parent = u.parent in transplant, and lift y's right child before y moves.
Chapter 6
Visit every node once, and choose the order by what the job needs
A traversal visits every node once. Three traversals are recursive. They differ only in when they visit the node: before, between or after its two subtrees. The fourth goes level by level with a queue.
| Walk | Order | Seven-key tree | Use |
|---|---|---|---|
| In-order | left, node, right | 2, 5, 7, 10, 12, 15, 20 | sorted output, validation |
| Preorder | node, left, right | 10, 5, 2, 7, 15, 12, 20 | save and copy a tree |
| Postorder | left, right, node | 2, 7, 5, 12, 20, 15, 10 | free a tree, children first |
| Level-order | top to bottom | 10, 5, 15, 2, 7, 12, 20 | print by level, width |
Choose a walk and press Play. The numbers on the nodes are the visit order. Only one walk reads left to right.
The seven-key tree from Chapter 1.
How much work is an in-order walk of n nodes? It visits each node once. It crosses each edge twice, once down and once back up. A tree with n nodes has n − 1 edges, because every node but the root hangs from one. Call the total steps W.
W equals n plus two times n minus one.
Count one step for each of the n nodes. Count two steps for each of the n − 1 edges. Add them. W grows in step with n, so the walk is Θ(n) whatever the shape.
The seven-key tree: W = 7 + 2 × 6 = 19 steps. A chain of the same seven keys also has 6 edges, so it also takes 19. A million nodes take about 3 million steps.
pythonfrom collections import deque def inorder(x, out): if x: inorder(x.left, out); out.append(x.key); inorder(x.right, out) def preorder(x, out): if x: out.append(x.key); preorder(x.left, out); preorder(x.right, out) def postorder(x, out): if x: postorder(x.left, out); postorder(x.right, out); out.append(x.key) def level_order(root): out, q = [], deque([root] if root else []) while q: x = q.popleft(); out.append(x.key) q.extend(c for c in (x.left, x.right) if c) return out
The recursive walks use stack space up to h. Morris traversal does an in-order walk in O(1) extra space. It adds a temporary pointer from each left subtree's maximum back up to its parent, then removes it.
The failure. Symptom: a script that deletes a folder tree fails with "directory not empty". Measure: print the order it deletes in; a parent comes before its children. Fix: delete in postorder, children first.
Chapter 7
Bound the height from both sides, and measure what random arrival gives you
Search, minimum, successor, insert and delete each cost at most h + 1 node visits. So how tall does the tree grow?
Call the number of keys n. Level 0 holds one node, level 1 at most two, level 2 at most four. A tree of height h holds at most 1 + 2 + … + 2h = 2h+1 − 1 nodes. That gives the smallest possible height. The largest is a chain.
The floor of log base two of n is at most h, which is at most n minus one.
Each level holds at most twice the level above. To fit n keys you need at least ⌊log₂ n⌋ + 1 levels. A chain adds one level per key, so h can reach n − 1.
n = 1,024: ⌊log₂ 1,024⌋ = 10, so 10 ≤ h ≤ 1,023. A search costs between 11 and 1,024 comparisons. Only the insertion order picks the number.
Pick an order and drag n. The ruler marks the smallest height in green, the chain in red and your tree in teal. Press Average 200 trees on Random.
Illustrative keys 1 to n. Zigzag inserts 1, n, 2, n − 1, …: it alternates ends and still builds a chain. The average uses 200 fresh shuffles.
Random order is the common case. Each insert makes one comparison per ancestor of the new node. So the cost to build the tree is the sum of all node depths. Call its expected value C(n). Call the n-th harmonic number Hn = 1 + 1/2 + … + 1/n.
C of n equals two times n plus one, times H-n, minus four n.
Add up Hn. Multiply it by 2(n + 1) and subtract 4n: that is C(n). Divide C(n) by n to get the average depth of a key. A successful search costs that depth plus one.
n = 15: H15 ≈ 3.318, so C(15) = 2 × 16 × 3.318 − 60 ≈ 46.2. The average depth is 46.2 / 15 ≈ 3.1. The perfect tree of 15 averages 2.27 and the chain averages 7.
Quicksort makes the same comparisons on the same order: the first key inserted is the first pivot. Our simulation puts the expected height at about 5.9 for n = 15, 15.8 for n = 255 and 21 for n = 1,024: about twice the minimum.
The failure. Symptom: a plain BST keyed by timestamp gets slower each day. Measure: compare the height with ⌊log₂ n⌋; a height near n − 1 means a chain. Fix: a self-balancing tree, which caps the height whatever the order.
Chapter 8
Pass each node the window its key must fit, and catch the key that breaks an ancestor's rule
Someone hands you a binary tree and says it is a BST. How do you check? The local test, "left child smaller, right child larger", is wrong. It misses a key deep in a subtree that breaks an ancestor's rule, like the planted 17 in Chapter 1.
The fix is to pass a window down. Each node gets the open range its key must lie in, built from all its ancestors. Call the bottom of the range lo and the top hi.
lo is less than x-dot-key, which is less than hi.
Give the root lo = minus infinity and hi = plus infinity. A left child gets (lo, x.key). A right child gets (x.key, hi). If any key falls outside its window, the tree is not a BST.
Root 15, its left child 10, and 10's right child 17. 10 gets (−∞, 15) and passes. 17 gets (10, 15), and 17 < 15 is false: invalid. The local test passes 17, because 17 > 10.
Pick a tree and a check, then press Run. Blue and pink under each node are its window. Red marks the first key outside it.
Toy trees made for this page. The local check compares each node with its children only.
pythondef is_bst(x, lo=float('-inf'), hi=float('inf')): if x is None: return True if not (lo < x.key < hi): return False return is_bst(x.left, lo, x.key) and is_bst(x.right, x.key, hi)
It visits each node once, so it is Θ(n) time and O(h) stack. A second correct check: run the in-order walk and confirm that each key is larger than the one before.
The failure. Symptom: a validator says "valid", yet a search misses a key. Measure: compare its verdict with an in-order walk of the same tree. Fix: pass the window down; never stop at the children.
Chapter 9
Cap the height with a balancing rule, and pick a tree over a hash table when order matters
A plain BST has no defense against sorted input. Production code uses a self-balancing BST. After each insert or delete it makes a few rotations: local pointer swaps that keep the in-order sequence and shorten the tall side.
| Tree | Balance rule | Height cap | Found in |
|---|---|---|---|
| AVL (1962) | at every node, the two subtree heights differ by at most 1 | about 1.44 log₂ n | read-heavy in-memory indexes |
| Red-black | colour rules (CLRS 13) | 2 log₂(n + 1) | C++ std::map in common libraries, Java TreeMap, the Linux kernel's rbtree |
| B-tree | t − 1 to 2t − 1 keys in each non-root node (CLRS 18) | about logt n | PostgreSQL and SQLite indexes, many file systems |
The red-black cap is the one CLRS proves. Call the number of keys n and the height h.
h is at most two times log base two of n plus one.
Add one to n. Take log base two. Double it. A red-black tree is never taller than that, in any insertion order.
n = 1,000,000: log₂(1,000,001) ≈ 19.93, so h ≤ 39 and a search makes at most 40 comparisons. A plain BST fed sorted IDs has h = 999,999.
When should you use a hash table instead? A hash table finds one exact key in about one step. A BST wins every job that needs order. A range query, "every key from lo to hi", walks down the tree and skips each subtree that lies wholly outside the range.
Drag the two ends of the range. Purple keys are in the range. Warm nodes are the others the query touched. The query never reaches the grey ones.
Illustrative: keys 3, 6, …, 93 in a perfect tree of height 4. A hash table must check all 31 keys, because it keeps no order.
For the range 20 to 40, the tree reports 7 keys and touches 11 nodes. A hash table checks all 31. The cost of the tree is O(h + k) for k reported keys.
The failure. Symptom: a "last 7 days" query on a hash index reads the whole table. Measure: compare rows read with rows returned. Fix: add an ordered index, a B-tree, on the timestamp.
Chapter 10
Keep the terms, the numbers, the checks and the core code on one page
A BST keeps smaller keys left and larger keys right, at every node, for whole subtrees. Search, minimum, maximum, successor, insert and delete each walk one path, so each costs O(h). The in-order walk lists the keys sorted in Θ(n). The order of arrival sets h, from ⌊log₂ n⌋ to n − 1, so real systems use a balanced tree.
| Term | Meaning | Number on this page |
|---|---|---|
| BST property | left subtree ≤ node ≤ right subtree, at every node | 17 under 10 breaks root 15 |
| Depth d, height h | edges from the root; depth of the deepest node | search costs d + 1 ≤ h + 1 |
| Successor | smallest larger key: right subtree's minimum, or first left turn going up | 10 → 12, 13 → 15 |
| Transplant | put the subtree at v where the subtree at u was | delete 10: 13 up, then 12 up |
| In-order walk | left, node, right: sorted keys | W = n + 2(n − 1) = 19 for n = 7 |
| Height bounds | ⌊log₂ n⌋ ≤ h ≤ n − 1 | 10 to 1,023 for n = 1,024 |
| Random BST | C(n) = 2(n + 1)Hn − 4n total depth | average depth 3.1 at n = 15; height about 21 at n = 1,024 |
| Window | lo < key < hi, from all ancestors | 17 gets (10, 15): invalid |
| Red-black cap | h ≤ 2 log₂(n + 1) | h ≤ 39 for a million keys |
pythonclass BST: def __init__(self): self.root = None def insert(self, k): y, x = None, self.root while x: y, x = x, (x.left if k < x.key else x.right) z = Node(k); z.parent = y if y is None: self.root = z elif k < y.key: y.left = z else: y.right = z def height(self, x='root'): x = self.root if x == 'root' else x return -1 if x is None else 1 + max(self.height(x.left), self.height(x.right)) t = BST() for k in [10, 5, 15, 2, 7, 12, 20]: t.insert(k) print(t.height()) # 2 s = BST() for k in range(1, 32): s.insert(k) print(s.height()) # 30: the chain from the hero
Now press Present or Teach. Explain from memory the two cases of successor and the three cases of delete, and say why a search costs at most h + 1. Then go back to the hero, switch from Sorted to Middle first, and say how many comparisons you saved.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 12, Binary Search Trees. The procedures follow the book; the devices, the toy trees and the simulated heights on this page are our own.