Sub topic 4
AVL trees: heights that differ by at most one
This chapter defines the AVL invariant, shows how to store and read it, and says what it does and doesn't promise. It assumes you can read Python and know the binary search tree (BST) ordering rule. It also assumes you know what a subtree's height is, that you have seen left and right rotations, and that you are comfortable with O(log n) versus O(n). Insertion, deletion, and the height proof each get their own chapter. Here we pin down the rule they all maintain.
The rule
An AVL tree is a binary search tree with one extra condition:
For every node, the heights of its left and right subtrees differ by at most one.
The condition applies to every node, not just the root. This is the most common misreading. A tree can have a root whose two subtrees have equal height and still violate the rule deeper down.
The name comes from the inventors, Adelson-Velsky and Landis, who published the structure in 1962. It was the first self-balancing BST.
Height conventions
Throughout this tutorial:
- An empty tree has height 0.
- A single node has height 1.
- A node's height is 1 plus the larger of its children's heights.
Some textbooks use -1 for the empty tree and 0 for a leaf. The balance factor comes out the same under either convention, as long as you use one convention consistently. Mixing them, for example by initializing new nodes to 0 while treating None as 0, is a real source of bugs.
Height counts nodes along the longest downward path. It is not depth, which is the distance from the root to a node.
The balance factor
Each node gets a balance factor:
balance factor = height(left subtree) - height(right subtree)In a valid AVL tree, every node's balance factor is -1, 0, or +1.
| Balance factor | Meaning | Valid in an AVL tree? |
|---|---|---|
| +1 | Left subtree is one taller | Yes |
| 0 | Both subtrees have equal height | Yes |
| -1 | Right subtree is one taller | Yes |
| +2 or more | Left-heavy beyond tolerance | No |
| -2 or less | Right-heavy beyond tolerance | No |
The sign tells you which side is heavy. The sign convention (left minus right) is arbitrary, but the code in this tutorial uses it everywhere, and the rebalancing cases in the next chapter depend on it.
A tree that looks balanced but is not
Look at this tree. The root has two subtrees of equal height, yet two other nodes break the rule.
The root passes the check because both subtrees have height 3. Node 5 fails because its left subtree has height 2 and its right subtree is empty. Node 20 fails for the same reason. A check that only looks at the root would accept this tree.
Storing height in each node
To read a balance factor you need subtree heights. Recomputing a height means walking the whole subtree, which costs O(n) and would destroy the point of the structure. Instead, each node caches its own height.
Two consequences follow:
- Reading a child's height is O(1), so computing a balance factor is O(1).
- Every operation that changes a node's children must refresh that node's cached height. Refresh children before parents, because a parent's height depends on its children's stored values.
Here is the node, the helper functions, and both rotations. The demo at the bottom builds the left-leaning chain from the diagram's left side and repairs it.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1 # height of a single node is 1; empty tree is 0
def height(n):
return n.height if n else 0
def update(n):
n.height = 1 + max(height(n.left), height(n.right))
def balance_factor(n):
return height(n.left) - height(n.right)
def rotate_right(y):
x = y.left
y.left = x.right
x.right = y
update(y)
update(x)
return x
def rotate_left(x):
y = x.right
x.right = y.left
y.left = x
update(x)
update(y)
return y
# Build a left-leaning chain 5 -> 3 -> 1 by hand, updating child first.
root = Node(5)
root.left = Node(3)
root.left.left = Node(1)
update(root.left)
update(root)
print(balance_factor(root)) # 2, so the AVL rule is violated
root = rotate_right(root)
print(root.key, root.height, balance_factor(root)) # 3 2 0The update function is the only place that computes a height. rotate_right and rotate_left call it for the lower node first (y in rotate_right), because after the rotation that node is a child of the other one. If you reversed the two calls, x would be computed from a stale height for y.
Why the rotation fixes this chain
Rotations preserve the BST ordering, which is why they can repair shape safely. In the demo, the chain 5, 3, 1 has all its weight on one side. Rotating right at 5 lifts 3 to the root, with 1 and 5 as its children. The result has balance factor 0 at every node.
You don't have to decide which rotation to use by hand in a full implementation. The next chapter covers the four imbalance cases and which rotation each one needs.
What the rule guarantees
The AVL rule bounds the height of the tree. An AVL tree with n nodes has height at most about 1.44 · log₂(n + 2). Searching, inserting, and deleting each walk a single root-to-leaf path, so each costs O(log n) in the worst case. A chapter later in this tutorial derives the bound.
The factor 1.44 matters when you compare designs. It says AVL trees are never much taller than a perfectly packed tree, which has height about log₂ n. Lookups on an AVL tree therefore make few comparisons.
Why the rule is easy to maintain
Starting from a valid AVL tree, one insertion or one deletion changes the height of any subtree by at most 1. So a node that had balance factor -1, 0, or +1 can reach at most -2 or +2 afterward, never ±3. This is why the repair needs only a small, fixed set of cases rather than an open-ended search. After a change, the code walks back up the path from the changed spot to the root and checks each node's balance factor.
Checking the invariant independently
Cached heights can be wrong if you forget an update call. A good test therefore recomputes heights from scratch and compares against the rule, without trusting any stored value. This version works on any binary node with key, left, and right.
class Plain:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def check_avl(n):
"""Return the height of n; raise ValueError if any node breaks the AVL rule."""
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: %d vs %d" % (n.key, lh, rh))
return 1 + max(lh, rh)
good = Plain(2, Plain(1), Plain(3))
print(check_avl(good)) # 2
bad = Plain(5, Plain(3, Plain(1)))
try:
check_avl(bad)
except ValueError as e:
print(e) # unbalanced at 5: 2 vs 0The function visits every node once, so it costs O(n). That is fine for tests and too slow for production lookups. A later chapter extends this idea into a full validator that also checks BST ordering and compares cached heights.
Common mistakes
- Checking only the root. The rule covers all nodes. The earlier diagram shows a tree that passes at the root and fails elsewhere.
- Forgetting to update heights after a rotation. The tree's shape changes, but stale heights make later balance factors wrong. Update the lower node first.
- Confusing height with depth. Height is measured from a node down to its deepest leaf. Depth is measured from the root down to the node.
- Mixing height conventions. If
Noneis 0, a new leaf must be 1. - Reading the rule as "the tree is perfectly balanced". AVL allows a skew of one level at every node. Node counts on the left and right of a node can still differ by a lot.
Summary of the working model
- The invariant: for every node, subtree heights differ by at most 1.
- Each node caches its height, so the balance factor is an O(1) read.
- A single insertion or deletion can push a balance factor to ±2 and no further, so a fixed set of rotation cases suffices.
- The invariant caps tree height at about 1.44 · log₂ n, which is what makes every operation O(log n).
Exercise
A node has a left subtree of height 3 and a right subtree of height 5. What is its balance factor, is it allowed in an AVL tree, and what is the node's cached height?
Show answer
The balance factor is 3 - 5 = -2. That is not allowed, because only -1, 0, and +1 are valid. The node is right-heavy. Its cached height would be 1 + max(3, 5) = 6.
Exercise
A tree has root 8 with left child 4 and right child 12. Node 4 has a left child 2. Node 12 has no children. Is this a valid AVL tree? Give the balance factor of every node.
Show answer
Yes. Node 2 has factor 0 and height 1. Node 4 has factor +1 (left height 1, right height 0) and height 2. Node 12 has factor 0 and height 1. The root 8 has left height 2 and right height 1, so its factor is +1 and its height is 3. Every factor is in -1..+1.
Exercise
Why must rotate_right call update(y) before update(x)?
Show answer
After the rotation, y is a child of x, so x's height depends on y's height. If x were updated first, it would use y's old height and store a wrong value.