Sub topic 4
AVL trees: heights that differ by at most one
This chapter assumes you can read Python and know how a plain binary search tree (BST) searches and inserts. It also assumes you know that tree height controls the cost of each operation, and that a rotation turns one subtree shape into another while keeping the key order. Here you learn the rule an AVL tree enforces and how to measure it. The next chapter uses that rule to repair the tree after an insertion.
The invariant
An AVL tree is a BST with one extra rule, which applies to every node:
> The heights of the node's left and right subtrees differ by at most 1.
Height here counts nodes on the longest downward path, so a single node has height 1 and an empty subtree has height 0. This matches the code below.
The rule applies to every node, not just the root. A tree can look balanced at the top and still break the rule deep inside it. Because the rule is local, you can check it, and repair it, one node at a time.
The balance factor
The balance factor of a node is the height of its left subtree minus the height of its right subtree. In an AVL tree it must be -1, 0, or 1.
| Balance factor | Meaning | Allowed? |
|---|---|---|
| 1 | Left subtree is one taller | Yes |
| 0 | Subtrees have equal height | Yes |
| -1 | Right subtree is one taller | Yes |
| 2 or more | Left side too tall | No, needs a rotation |
| -2 or less | Right side too tall | No, needs a rotation |
A single insertion or deletion changes a subtree height by at most 1. So a violating node always has a balance factor of exactly 2 or -2, never more.
Storing heights in nodes
Recomputing a height by walking the whole subtree would cost O(n). Instead, each node caches its own height. After any change below a node, you call update on it, working from the child up to the parent.
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 yEach rotation returns the new root of the subtree, so the caller must store the result in the parent's link. The order of the two update calls matters. The node that moved down is now the child, so it is updated first.
A violation and its repair
Take three keys inserted in the order 10, 5, 2 with no rebalancing. They form a chain that leans left.
Node 10 has a left subtree of height 2 and an empty right subtree, so its balance factor is 2. A right rotation at 10 fixes it:
y = Node(10)
y.left = Node(5)
y.left.left = Node(2)
update(y.left)
update(y)
print(balance_factor(y)) # 2: the invariant is broken
root = rotate_right(y)
print(root.key, root.height, balance_factor(root)) # 5 2 0The key 5 is now the root, with 2 on the left and 10 on the right. The in-order sequence is still 2, 5, 10, and every balance factor is back in range.
Common errors
- Counting an empty tree as height 1, or a single node as height 0, and then mixing the two conventions. Pick one and use it everywhere.
- Calling
updateon the parent before the child during a rotation, which leaves a stale height. - Forgetting to assign the rotation's return value to the parent link, which detaches the subtree.
- Checking balance only at the root instead of at every node on the path.
Exercise
A node has a left subtree of height 3 and a right subtree of height 1. What is its balance factor, and is the AVL invariant satisfied? What would the balance factor be if the right subtree had height 2?
Show answer
The balance factor is 3 - 1 = 2, so the invariant is violated and the node needs rebalancing. With a right subtree of height 2, the balance factor would be 3 - 2 = 1, which is allowed.