Sub topic 7
Why AVL Trees Have Logarithmic Height
This chapter assumes you have read the earlier chapters on the AVL invariant and on insertion and deletion. You should be comfortable with recurrences, mathematical induction at a basic level, and logarithms. Height here follows the chapter code: an empty tree has height 0 and a single node has height 1.
The AVL invariant says that at every node the two subtrees differ in height by at most one. That rule never mentions the number of nodes. This chapter shows that the rule still forces the height to be O(log n), so search, insertion, and deletion all cost O(log n).
The question to ask backwards
Counting how tall a tree of n nodes can get is awkward. It is easier to ask the reverse: what is the fewest nodes an AVL tree of height h can have? Call that number N(h).
If you know N(h), you can bound the height. An AVL tree with n nodes and height h must satisfy n >= N(h). If N(h) grows exponentially in h, then h can grow only logarithmically in n.
The sparsest AVL tree
To make a tree of height h with as few nodes as possible, build the thinnest tree the invariant allows:
- The root has two subtrees. At least one must have height
h - 1, otherwise the whole tree would not have height h. - The other subtree may be one level shorter, with height
h - 2. The invariant forbids anything shorter. - Each subtree should itself be as sparse as possible, so apply the same rule recursively.
Making the shorter side as short as the invariant allows removes the most nodes. This gives the recurrence:
N(0) = 0
N(1) = 1
N(h) = N(h-1) + N(h-2) + 1 for h >= 2The + 1 counts the root. The recurrence looks like the Fibonacci recurrence with an extra constant, which is why AVL trees are tied to Fibonacci numbers.
In every one of these trees, each internal node is lopsided by exactly one level. That lopsidedness is the worst case the invariant allows.
Computing N(h)
The code below evaluates the recurrence iteratively. It is the same function from the chapter's code examples.
def min_nodes(h):
"""Fewest nodes an AVL tree of height h can have: N(h) = N(h-1) + N(h-2) + 1."""
if h == 0:
return 0
a, b = 0, 1 # N(0), N(1)
for _ in range(h - 1):
a, b = b, a + b + 1
return b
print([min_nodes(h) for h in range(1, 6)]) # [1, 2, 4, 7, 12]The pair (a, b) holds N(h-2) and N(h-1). Each loop step advances it by one height, so after h - 1 steps b is N(h).
Building the sparsest tree for real
A formula is easy to get wrong, so the next program constructs the sparsest tree and checks it. It builds the left subtree with height h - 1 and the right with height h - 2. It assigns keys in order, so the result is a valid BST. A checker then confirms that every node satisfies the AVL invariant and that the cached heights are right.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
def min_nodes(h):
if h == 0:
return 0
a, b = 0, 1
for _ in range(h - 1):
a, b = b, a + b + 1
return b
def build(h, next_key):
"""Return (root, next unused key) for the sparsest AVL tree of height h."""
if h == 0:
return None, next_key
left, next_key = build(h - 1, next_key)
node = Node(next_key)
next_key += 1
right, next_key = build(max(h - 2, 0), next_key)
node.left, node.right = left, right
node.height = h
return node, next_key
def check_avl(n):
"""Return the true height of n, raising ValueError if the AVL invariant fails."""
if n is None:
return 0
lh = check_avl(n.left)
rh = check_avl(n.right)
if abs(lh - rh) > 1:
raise ValueError("unbalanced at %r" % n.key)
h = 1 + max(lh, rh)
if h != n.height:
raise ValueError("stale height at %r" % n.key)
return h
counts = []
for h in range(1, 9):
root, next_key = build(h, 1)
assert check_avl(root) == h
count = next_key - 1
assert count == min_nodes(h)
counts.append(count)
print(counts) # [1, 2, 4, 7, 12, 20, 33, 54]Every tree passes the AVL check, and its size matches min_nodes. This shows that N(h) is the size of a tree that exists. It does not yet show that no smaller tree exists. The argument for that is the one above: any AVL tree of height h has a subtree of height h - 1 and another of height at least h - 2. By induction, each of those has at least N(h-1) and N(h-2) nodes.
The Fibonacci connection
Compare the sizes with the Fibonacci numbers F(1) = F(2) = 1, F(k) = F(k-1) + F(k-2):
| h | N(h) | N(h) + 1 | F(h+2) | 1.618^h |
|---|---|---|---|---|
| 1 | 1 | 2 | 2 | 1.62 |
| 2 | 2 | 3 | 3 | 2.62 |
| 3 | 4 | 5 | 5 | 4.24 |
| 4 | 7 | 8 | 8 | 6.85 |
| 5 | 12 | 13 | 13 | 11.09 |
| 6 | 20 | 21 | 21 | 17.94 |
| 7 | 33 | 34 | 34 | 29.03 |
| 8 | 54 | 55 | 55 | 46.98 |
The columns N(h) + 1 and F(h+2) are identical, so N(h) = F(h+2) - 1. You can prove this by induction. If N(h-1) + 1 = F(h+1) and N(h-2) + 1 = F(h), then adding gives N(h) + 1 = (N(h-1) + 1) + (N(h-2) + 1) = F(h+1) + F(h) = F(h+2). The + 1 terms work out because each addition brings two of them and the root brings one fewer.
Fibonacci numbers grow like φ^k, where φ = (1 + √5) / 2 ≈ 1.618 is the golden ratio. That is exponential growth, and the last column of the table shows φ^h staying below N(h) + 1.
A self-contained proof of the bound
You do not need Fibonacci closed forms to get the bound. The claim is:
N(h) + 1 >= φ^h for every h >= 0Base cases. For h = 0, N(0) + 1 = 1 = φ^0. For h = 1, N(1) + 1 = 2 >= φ.
Inductive step. Assume the claim holds for h - 1 and h - 2. Then:
N(h) + 1 = (N(h-1) + 1) + (N(h-2) + 1)
>= φ^(h-1) + φ^(h-2)
= φ^(h-2) * (φ + 1)
= φ^(h-2) * φ^2
= φ^hThe step φ + 1 = φ^2 holds because φ is the positive root of x^2 = x + 1. This is the exact reason φ appears.
Now take an AVL tree with n nodes and height h. Then n >= N(h), so n + 1 >= N(h) + 1 >= φ^h. Taking logarithms gives:
h <= log_φ(n + 1) = log2(n + 1) / log2(φ) ≈ 1.4404 * log2(n + 1)The lower bound is the usual one for any binary tree: a tree of height h holds at most 2^h - 1 nodes, so h >= log2(n + 1). Combined:
log2(n + 1) <= h <= 1.4404 * log2(n + 1)An AVL tree is never more than about 44% taller than a perfectly packed tree. The tighter constant in the literature, h < 1.4405 log2(n + 2) - 0.328, comes from using the exact closed form of the Fibonacci numbers.
What the bound means in numbers
The table shows the tallest an AVL tree of n nodes can be. For each n, it uses the largest h with N(h) <= n.
| n | Perfect tree height | Worst AVL height |
|---|---|---|
| 7 | 3 | 4 |
| 1,000 | 10 | 14 |
| 1,000,000 | 20 | 28 |
For example, N(28) = F(30) - 1 = 832,039 is at most one million, while N(29) = F(31) - 1 = 1,346,268 is above it. So no AVL tree with a million nodes has height 29 or more.
From height to running time
Search follows one root-to-leaf path, so it takes at most h steps, which is O(log n). Insertion and deletion, as written in the earlier chapters, recurse down one path and then run rebalance on each node on the way back up. Each rebalance call does a constant amount of work: it updates a height, computes a balance factor, and performs at most two rotations. That is O(h) in total, which is O(log n).
The bound also explains why the invariant must hold everywhere. If one node could be off by two, the sparsest-tree recurrence would change to N(h) = N(h-1) + N(h-3) + 1 or worse. The growth rate would drop, and the proof would fail. Rebalancing after every update is what keeps the recurrence true.
Common mistakes
- Mixing height conventions. If you count an empty tree as height -1 and a single node as height 0, then
N(h)shifts by one and the table values move. Pick one convention and keep it. The formulas here use empty = 0. - Using the wrong subtree height for the sparsest tree. The shorter side has height
h - 2, noth - 1. Usingh - 1for both gives a perfect-looking tree withN(h) = 2N(h-1) + 1, which is the best case. - Forgetting the root. Dropping the
+ 1gives a pure Fibonacci recurrence, and the table would no longer matchF(h+2) - 1. - Treating 1.44 as a typical cost. It is the upper limit. It does not predict the average.
Exercise
Suppose an AVL tree of height 6 is built so that it has as few nodes as possible. How many nodes does it have, and what are the node counts of its two subtrees? Then use the table to state the largest height an AVL tree with 30 nodes can have.
Show answer
N(6) = N(5) + N(4) + 1 = 12 + 7 + 1 = 20 nodes. The subtrees are the sparsest trees of heights 5 and 4, with 12 and 7 nodes. For 30 nodes, N(7) = 33 is more than 30, while N(6) = 20 is at most 30. A height-7 AVL tree needs at least 33 nodes, so the largest possible height is 6.
Exercise
Explain why the proof breaks if the invariant is relaxed so that subtree heights may differ by at most two. What recurrence replaces N(h), and is the height still logarithmic?
Show answer
The sparsest tree now has one subtree of height h-1 and the other of height h-3, so N(h) = N(h-1) + N(h-3) + 1. This still grows exponentially, with a base of about 1.4656, the real root of x^3 = x^2 + 1. The height is still O(log n), with a larger constant, about 1.8 * log2 n. The proof pattern holds for any fixed allowed difference, but the trees get taller. The invariant must also be maintained by rebalancing, so the constant only changes the trade-off between height and rebalancing work.