Sub topic 5
AVL insertion and the four imbalance cases
This chapter assumes you know BST insertion, recursion, and the rotations and balance factor from the previous chapters. Here you will put them together into a working AVL insert.
The idea
AVL insertion has two steps. First, insert the key as in a plain BST. Second, walk back up the path to the root. At each ancestor, refresh its cached height and check its balance factor.
The balance factor of a node is height(left) - height(right). A valid AVL node has a balance factor of -1, 0, or 1. After one insertion, an ancestor can reach +2 or -2, and no further. A rotation at that ancestor repairs it.
Recursion gives you the walk back up for free. Each call returns the root of its (possibly rotated) subtree, and the parent stores that result.
The four cases
Let n be the lowest unbalanced node. Which fix applies depends on which side is heavy and where the extra height sits.
| Case | Balance of `n` | Balance of heavy child | Fix |
|---|---|---|---|
| Left-left | +2 | 0 or +1 | Rotate right at `n` |
| Left-right | +2 | -1 | Rotate left at `n.left`, then rotate right at `n` |
| Right-right | -2 | 0 or -1 | Rotate left at `n` |
| Right-left | -2 | +1 | Rotate right at `n.right`, then rotate left at `n` |
In the left-left and right-right cases, the new key went into the outer subtree of the heavy child, so one rotation lifts that child to the top. In the left-right and right-left cases, the new key went into the inner subtree. A single rotation would only move the problem to the other side. The first rotation turns the inner case into an outer case, and the second finishes the job.
The code
This code reuses Node, height, update, balance_factor, rotate_left and rotate_right from the previous chapter. The helper rebalance handles all four cases.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
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)
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 3Inserting 1 through 7 in order produces a perfectly balanced tree with 4 at the root and height 3. A plain BST would have height 7.
Why one repair is enough
An insertion raises the height of a subtree by at most 1. The lowest node that becomes unbalanced is repaired by a rotation, and the rotation returns that subtree to the height it had before the insertion. Every ancestor above it therefore sees no net height change. Their rebalance calls still run, but they find balance factors within range. So AVL insertion needs at most one single or double rotation, and the cost stays O(log n).
Common errors
- Skipping the
updatecall. Cached heights go stale and balance factors become wrong.rebalancecallsupdatefirst for this reason. - Updating heights parent first in a rotation. The old parent becomes the child, so update it first. The new root is updated second.
- Checking the wrong child. For
bf > 1, test the balance ofn.left. Forbf < -1, testn.right. - Not assigning the return value.
n.left = rotate_left(n.left)is required. The rotation returns the new subtree root. - Treating a balance of 0 in the child as a double-rotation case. After insertion this does not occur at the unbalanced node. After deletion it does, and single rotation is the correct fix.
Exercise
Insert 30, 10, 20 into an empty AVL tree, in that order. Which case occurs, which rotations fix it, and what is the final root?
Show answer
After inserting 20, node 30 has balance factor +2 and its left child 10 has balance factor -1, so this is the left-right case. Rotate left at 10, which makes 20 the left child of 30. Then rotate right at 30. The final tree has 20 as the root, with 10 as its left child and 30 as its right child.
Exercise
In rebalance, why does the code call update(n) before computing the balance factor?
Show answer
A child's subtree may have changed during the recursive insertion, so the cached height of n may be stale. Updating first makes balance_factor(n) use the correct height.