Binary Search Trees

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.

Build one tree three ways

31

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

The Contact List

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.

Grow the contact list

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.

10,000

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.

The road

  1. The BST property: the one rule that orders the tree.
  2. Search, minimum, maximum: one path down, h + 1 comparisons at most.
  3. Successor: the next key in sorted order, in two cases.
  4. Insertion: search, then hang a leaf.
  5. Deletion: three cases and the transplant helper.
  6. Four walks: in-order, preorder, postorder, level-order.
  7. Height is everything: the hero's ruler, made exact (the showcase).
  8. Validating a tree: pass a window down.
  9. Balanced trees and hash tables: what production code uses.
  10. The field guide: terms, numbers, code and the credit.
You need search, insert and delete in about log n steps, and a sorted listing of all keys in about n steps. Which structure gives all four?

Chapter 1

The BST Property

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.

10 / \ 5 15 / \ / \ 2 7 12 20

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.

Say it aloud

y-dot-key is at most x-dot-key, which is at most z-dot-key.

y.key
y dot key the key of any node in x's left subtree, at any depth.
≤
is at most no larger than. This page uses distinct keys, so it is always strictly smaller.
x.key
x dot key the key of the node we check. Every node takes a turn as x.
z.key
z dot key the key of any node in x's right subtree, at any depth.
In plain words

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.

With numbers

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.

Check the rule at each node

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.

Node 15 has left child 10, and 10 has right child 17. Is this a valid BST?

Chapter 2

Search, Minimum and Maximum

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.

Trace a search

Pick a key and press Search. Warm nodes are the comparisons, in order. Try a key that is missing.

13

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.

Say it aloud

c equals d plus one, which is at most h plus one.

c
c the comparisons the search makes, one for each node it visits.
d
d the depth of the last node visited: the found node, or the node whose empty child ends a miss.
+ 1
plus one the root sits at depth 0 and still costs a comparison.
h
h the height of the tree: the depth of its deepest node.
In plain words

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.

With numbers

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.

You insert 2, 5, 7, 10, 12, 15, 20 in that order, then search for 20. How many comparisons does the search make?

Chapter 3

Successor and Predecessor

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.

  1. x has a right subtree. The successor is the minimum of that subtree. Step right once, then go left to the end.
  2. x has no right subtree. Climb toward the root. While you climb up from a right child, keep going. The first time you climb up from a left child, that parent is the successor. If you pass the root, x is the maximum and has no successor.

Find the next key

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.

Node 25 has right child 30. 30 has left child 27, and 27 has left child 26. What is the successor of 25?

Chapter 4

Insertion

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.

Hang a new leaf

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.

13

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.

You insert 3, 1, 5, 2, 4 into an empty BST. What do you get?

Chapter 5

Deletion

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.

Casez hasWhat to do
1no childrenRemove z. Its parent's pointer becomes empty.
2one childLift the child into z's place.
3two childrenFind 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.

Delete a node

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.

You delete a node with two children. Its successor y has a right child. What happens to that child?

Chapter 6

Four Ways to Walk a Tree

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.

WalkOrderSeven-key treeUse
In-orderleft, node, right2, 5, 7, 10, 12, 15, 20sorted output, validation
Preordernode, left, right10, 5, 2, 7, 15, 12, 20save and copy a tree
Postorderleft, right, node2, 7, 5, 12, 20, 15, 10free a tree, children first
Level-ordertop to bottom10, 5, 15, 2, 7, 12, 20print by level, width

Walk the tree four ways

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.

Say it aloud

W equals n plus two times n minus one.

W
W the total steps of the walk: visits plus edge crossings.
n
n the number of nodes. The walk visits each one once.
2
two times the walk crosses each edge down once and back up once.
n − 1
n minus one the number of edges in a tree of n nodes.
In plain words

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.

With numbers

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.

You must free every node of a tree, and a freed node's pointers are gone. Which walk is safe?

Chapter 7

Height Is Everything

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.

Say it aloud

The floor of log base two of n is at most h, which is at most n minus one.

⌊log₂ n⌋
the floor of log base two of n how many times you can halve n before it drops below 2. The floor rounds down.
≤
is at most
h
h the height of a BST holding n keys.
n − 1
n minus one the height of a chain, where every node has one child.
In plain words

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.

With numbers

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.

Grow trees from different orders

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.

63

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.

Say it aloud

C of n equals two times n plus one, times H-n, minus four n.

C(n)
C of n the expected total comparisons to build the tree from a random order. It equals the expected sum of all node depths.
2(n + 1)
two times n plus one n is the number of keys.
Hn
H-n the harmonic number 1 + 1/2 + … + 1/n. It is close to the natural log of n, plus 0.58.
4n
four n a correction that grows in step with n.
In plain words

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.

With numbers

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.

A BST holds 1,024 keys. How many comparisons can a search cost in the worst tree (a chain) and in the best tree?

Chapter 8

Validating a Tree

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.

Say it aloud

lo is less than x-dot-key, which is less than hi.

lo
lo the floor: the key of the nearest ancestor that has x in its right subtree, or minus infinity.
<
is less than strict, because keys are distinct.
x.key
x dot key the key of the node we check.
hi
hi the ceiling: the key of the nearest ancestor that has x in its left subtree, or plus infinity.
In plain words

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.

With numbers

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.

Run both validators

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.

Why is "each left child is smaller and each right child is larger" not enough to validate a BST?

Chapter 9

Balanced Trees and Hash Tables

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.

TreeBalance ruleHeight capFound in
AVL (1962)at every node, the two subtree heights differ by at most 1about 1.44 log₂ nread-heavy in-memory indexes
Red-blackcolour rules (CLRS 13)2 log₂(n + 1)C++ std::map in common libraries, Java TreeMap, the Linux kernel's rbtree
B-treet − 1 to 2t − 1 keys in each non-root node (CLRS 18)about logt nPostgreSQL 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.

Say it aloud

h is at most two times log base two of n plus one.

h
h the height of a red-black tree holding n keys.
2
two times the longest path is at most twice the shortest, by the colour rules.
log₂(n + 1)
log base two of n plus one the height of a perfect tree with n keys, plus about one.
In plain words

Add one to n. Take log base two. Double it. A red-black tree is never taller than that, in any insertion order.

With numbers

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.

Ask for a 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.

20
40

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.

An in-memory store needs exact lookups, range queries and listing keys in order. Which structure fits?

Chapter 10

The Field Guide

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.

Terms and numbers

TermMeaningNumber on this page
BST propertyleft subtree ≤ node ≤ right subtree, at every node17 under 10 breaks root 15
Depth d, height hedges from the root; depth of the deepest nodesearch costs d + 1 ≤ h + 1
Successorsmallest larger key: right subtree's minimum, or first left turn going up10 → 12, 13 → 15
Transplantput the subtree at v where the subtree at u wasdelete 10: 13 up, then 12 up
In-order walkleft, node, right: sorted keysW = n + 2(n − 1) = 19 for n = 7
Height bounds⌊log₂ n⌋ ≤ h ≤ n − 110 to 1,023 for n = 1,024
Random BSTC(n) = 2(n + 1)Hn − 4n total depthaverage depth 3.1 at n = 15; height about 21 at n = 1,024
Windowlo < key < hi, from all ancestors17 gets (10, 15): invalid
Red-black caph ≤ 2 log₂(n + 1)h ≤ 39 for a million keys

Before you ship a tree

  1. Ask whether keys can arrive sorted. If yes, use a balanced tree.
  2. Pick a rule for equal keys: refuse, count, or always go one side.
  3. Write search and walks as loops if the height can pass 1,000.
  4. After any change to delete, check every parent pointer and the in-order walk.
  5. Validate with windows, never with the children alone.
  6. Use a hash table only if no query needs order.

The core code

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

Keep going

The takeaway. Every BST operation costs the height. Ask how the keys will arrive, and if they can arrive in order, cap the height with a balanced tree.
Why do libraries ship red-black trees instead of plain BSTs?

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.

Source

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.

CLRS Chapter 12 · Binary Search Trees
Next: Red-Black Trees · Back to Gleams