Sub topic 5
AVL insertion and the four imbalance cases
This chapter assumes you can read recursive Python and can do plain binary search tree (BST) insertion. It also assumes you know what an AVL tree guarantees: at every node, the heights of the left and right subtrees differ by at most one. You should already have met left and right rotations. The code below repeats them so the chapter runs on its own.
The shape of the algorithm
AVL insertion is a plain BST insertion plus one extra step. After the recursive call returns at each node on the path, you recompute that node's height and check its balance factor. If the balance factor has left the range -1 to 1, you repair the node with one or two rotations.
The balance factor used here is height(left) - height(right). A positive value means left-heavy and a negative value means right-heavy.
Three facts make the repair small and predictable:
- Only the nodes on the path from the root to the new leaf can change height. Every other subtree is untouched.
- Inserting one key raises any subtree's height by at most 1. A node that was balanced (-1, 0 or 1) can therefore reach at most +2 or -2, never +3.
- The repair is local. You rebalance the lowest unbalanced node on the path, and that is enough.
The four cases
When a node n reaches balance factor +2 or -2, the new key went into one of four places relative to n. The names say where the extra height sits: first the child of n, then the grandchild.
| Case | Test at `n` | Test at the heavy child | Repair |
|---|---|---|---|
| Left-left | balance factor > 1 | left child's balance factor >= 0 | `rotate_right(n)` |
| Left-right | balance factor > 1 | left child's balance factor < 0 | `rotate_left(n.left)`, then `rotate_right(n)` |
| Right-right | balance factor < -1 | right child's balance factor <= 0 | `rotate_left(n)` |
| Right-left | balance factor < -1 | right child's balance factor > 0 | `rotate_right(n.right)`, then `rotate_left(n)` |
Left-left and right-right are the "straight line" cases. The tree leans the same way for two steps, and one rotation at n flattens it.
Left-right and right-left are the "zig-zag" cases. A single rotation at n would only move the problem to the other side, because the heavy grandchild stays on the inside. The first rotation, at the child, turns the zig-zag into a straight line. The second rotation at n then fixes the line.
The tests look at the child's balance factor, not the grandchild's. Pick the child on the heavy side, then ask which way that child leans.
Working code
This block contains the node, the rotations, rebalance and insert. It also has a small preorder helper so you can see the tree's shape. It runs as shown.
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
def rebalance(n):
update(n)
bf = balance_factor(n)
if bf > 1: # left-heavy
if balance_factor(n.left) < 0: # left-right case
n.left = rotate_left(n.left)
return rotate_right(n)
if bf < -1: # right-heavy
if balance_factor(n.right) > 0: # right-left case
n.right = rotate_right(n.right)
return rotate_left(n)
return n
def insert(n, key):
if n is None:
return Node(key)
if key < n.key:
n.left = insert(n.left, key)
elif key > n.key:
n.right = insert(n.right, key)
else:
return n # ignore duplicates
return rebalance(n)
def preorder(n):
if n is None:
return []
return [n.key] + preorder(n.left) + preorder(n.right)
# One input order per case. Each ends as root 2 with children 1 and 3.
cases = {
"left-left": [3, 2, 1],
"left-right": [3, 1, 2],
"right-right": [1, 2, 3],
"right-left": [1, 3, 2],
}
for name, keys in cases.items():
root = None
for k in keys:
root = insert(root, k)
print(name, preorder(root)) # [2, 1, 3] every time
root = None
for k in range(1, 8): # sorted input would make a plain BST a list
root = insert(root, k)
print(root.key, root.height) # 4 3Each of the four three-key inputs produces the same balanced tree, which shows that the four repairs reach the same shape from different starting points.
Tracing a zig-zag
Take the left-right case, inserting 3, then 1, then 2.
- Insert 3. The tree is the single node 3.
- Insert 1. It becomes the left child of 3. Node 3 has balance factor +1, which is allowed.
- Insert 2. It goes left of 3, then right of 1. On the way back up,
rebalance(1)finds balance factor -1 and does nothing. Thenrebalance(3)sees height 2 on the left and 0 on the right, so the balance factor is +2. - The left child, 1, has balance factor -1, which is less than 0. This is the left-right case.
rotate_left(1)makes 2 the left child of 3, with 1 as the left child of 2. The tree is now a straight left-left line: 3, 2, 1.rotate_right(3)lifts 2 to the root, with 1 and 3 as its children.
Both rotations return the new subtree root, and the caller stores it: n.left = rotate_left(n.left) in the first and return rotate_right(n) in the second. If you drop either assignment, the parent keeps pointing at the old root and part of the tree is lost.
The decision at each node
Why one repair is enough
Suppose a subtree rooted at n had height h before the insertion, and the insertion made it h + 1 and unbalanced it. After the single or double rotation, the new root of that subtree has height h again. Its ancestors then see the same subtree height as before the insertion, so their balance factors do not change. No further rotation is needed higher up.
Insertion therefore performs at most one rotation case per call (one single or one double rotation). The code above still calls rebalance on every ancestor, but those calls only recompute the same heights. This costs O(log n) in total, since the height of an AVL tree is logarithmic. An optimized version could stop early once a node's height does not change, but the simple version is easier to get right.
Edge cases
- Duplicates. The
elsebranch returns the node unchanged. Becauserebalanceis skipped, no heights change. If you want a multiset, store a count in the node instead of inserting a second copy. - Balance factor 0 at the child. During insertion, a child of an unbalanced node never has balance factor 0, so the tests
< 0and> 0are unambiguous. During deletion a child can have balance factor 0, and then a single rotation is the correct repair. The tests inrebalancealready send that case to a single rotation, so the same function works for both operations. - Recursion depth. The recursion depth equals the tree height, which is about 1.44 log2(n) at worst. Even a million keys need only about 29 levels, so Python's recursion limit is not a concern.
- Empty input.
insert(None, key)returns a new node, which is how the tree starts.
Common errors
- Stale heights. Calling
rotate_right(n)without updatingnfirst means the child's balance factor is computed from old heights.rebalancecallsupdate(n)before testing, and each rotation updates the lower node before the upper one. Keep that order. - Updating the new root first. In a rotation, the old root becomes a child of the new root. Its height must be correct before the new root's height is computed from it.
- Testing the wrong node. In the left-right check, the question is about
n.left, notn.left.rightand notnitself. - Not storing the result. Rotations return a new subtree root. Every call site must assign it to the parent's link or return it.
- Rebalancing only at the leaf. The imbalance appears at an ancestor, so
rebalancemust run on every node on the way back up, not only on the new node's parent.
Exercises
Exercise
Insert the keys 10, 20, 30, 25, 28 in that order into an empty AVL tree. Which case occurs, at which node, and what is the final preorder?
Show answer
After 10, 20, 30 the tree is root 20 with children 10 and 30 (a right-right repair at 10 along the way). Inserting 25 goes under 30 as its left child, and no node is out of balance. Inserting 28 goes 20, 30, 25, then right of 25. Node 30 now has height 2 on the left and 0 on the right, so its balance factor is +2. Its left child 25 has balance factor -1, so this is the left-right case at node 30. Rotate left at 25 (28 becomes the left child of 30, with 25 below it), then rotate right at 30. The subtree root is 28 with children 25 and 30. The final preorder is [20, 10, 28, 25, 30], and the height is 3.
Exercise
A student changes the first test in the left-heavy branch of rebalance from "balancefactor(n.left) < 0" to "balancefactor(n.left) <= 0". Inserting keys never breaks, but deleting keys sometimes leaves a node with balance factor 2 after rebalancing. Why?
Show answer
When the left child has balance factor 0, which can happen after a deletion but not after an insertion, the change sends the node to the double rotation. A double rotation does not restore balance in that situation, because the left child's two subtrees have equal height and the left-right pre-rotation leaves the node still too heavy. The correct repair for balance factor 0 at the child is a single rotation, so the test must stay strictly less than 0.