Sub topic 6
AVL deletion and rebalancing on the way up
This chapter assumes you have read the earlier chapters on rotations, the AVL invariant, and AVL insertion. You should know the balance factor (height of left subtree minus height of right subtree), the rotate_left and rotate_right helpers, and the rebalance function. You should also be comfortable with recursive BST deletion.
Why deletion needs more care than insertion
An AVL insertion adds one node, so at most one subtree grows. After the first rebalance, whether a single or a double rotation, that subtree returns to the height it had before the insert. No ancestor above it can be out of balance, so insertion needs at most one rebalancing step.
Deletion works the other way. Removing a node can shrink a subtree. The shrink makes the sibling side too heavy, and a rotation that fixes the imbalance can itself leave the subtree one level shorter than before. Then the parent sees a height change it did not expect and may become unbalanced too. A single deletion can therefore trigger a rotation at every level on the path back to the root.
For this reason the deletion code does not stop at the first rotation. It rebalances every ancestor on the return path.
The two phases
- Remove the node as in a plain BST. There are three cases:
- A leaf is removed.
- A node with one child is replaced by that child.
- A node with two children takes the key of its in-order successor (the smallest key in its right subtree), and then the successor node is deleted from the right subtree.
- Rebalance on the way up. Each recursive call returns the new root of its subtree. The caller stores it as its child, then runs
rebalanceon itself.rebalancerecomputes the height, checks the balance factor, and rotates if the factor is outside the range -1 to 1.
The "0 or 1 child" case returns early without calling rebalance on the removed node, because that node no longer exists. Its parent still rebalances after the recursive call returns.
Which rotation to use
The choice depends on the balance factor of the node and of its taller child.
| Node balance factor | Taller child's balance factor | Case | Action |
|---|---|---|---|
| +2 | +1 | left-left | rotate right at node |
| +2 | 0 | left-left (deletion only) | rotate right at node |
| +2 | -1 | left-right | rotate left at child, then rotate right at node |
| -2 | -1 | right-right | rotate left at node |
| -2 | 0 | right-right (deletion only) | rotate left at node |
| -2 | +1 | right-left | rotate right at child, then rotate left at node |
The rows with a child factor of 0 never occur after an insertion. After a deletion they can. The taller child may have two subtrees of equal height, because the deletion happened on the other side. A single rotation is correct there. The rebalance function from the insertion chapter already handles this. It tests balance_factor(n.left) < 0 and balance_factor(n.right) > 0 with strict inequalities, so a factor of 0 falls through to the single rotation.
Complete code
This block holds everything needed to run deletion, including a validator and a randomized test.
import random
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:
if balance_factor(n.left) < 0:
n.left = rotate_left(n.left)
return rotate_right(n)
if bf < -1:
if balance_factor(n.right) > 0:
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
return rebalance(n)
def min_node(n):
while n.left:
n = n.left
return n
def delete(n, key):
if n is None:
return None
if key < n.key:
n.left = delete(n.left, key)
elif key > n.key:
n.right = delete(n.right, key)
else:
if n.left is None:
return n.right
if n.right is None:
return n.left
successor = min_node(n.right)
n.key = successor.key
n.right = delete(n.right, successor.key)
return rebalance(n)
def check_avl(n, lo=None, hi=None):
"""Return the true height, raising ValueError if any invariant fails."""
if n is None:
return 0
if (lo is not None and n.key <= lo) or (hi is not None and n.key >= hi):
raise ValueError("BST order violated at %r" % n.key)
lh = check_avl(n.left, lo, n.key)
rh = check_avl(n.right, n.key, hi)
if abs(lh - rh) > 1:
raise ValueError("unbalanced at %r" % n.key)
if n.height != 1 + max(lh, rh):
raise ValueError("stale height at %r" % n.key)
return 1 + max(lh, rh)
# Worked example: the taller child has balance factor 0.
root = None
for k in (2, 1, 4, 3, 5):
root = insert(root, k)
root = delete(root, 1)
print(root.key, root.height, root.left.key, root.left.right.key, root.right.key)
# 4 3 2 3 5
# Randomized test: delete everything in random order, checking after each step.
random.seed(1)
keys = random.sample(range(1000), 300)
root = None
for k in keys:
root = insert(root, k)
check_avl(root)
random.shuffle(keys)
for k in keys:
root = delete(root, k)
check_avl(root)
print(root is None) # TrueWorked example
Insert 2, 1, 4, 3, 5 in that order. No rotation happens, and the tree looks like this:
- Root 2 has left child 1 and right child 4.
- Node 4 has left child 3 and right child 5.
- The tree has height 3.
Now delete 1.
- The recursion goes left from 2 and finds 1, which has no children. It returns
None. - Back at node 2, the left child is
None(height 0) and the right subtree rooted at 4 has height 2. The balance factor is -2. - The right child 4 has balance factor 0, because 3 and 5 are both leaves. This is the deletion-only case, so a single left rotation at 2 is enough.
- Node 4 becomes the root. Node 2 becomes its left child and keeps 3 as its right child. Node 5 stays on the right.
The final height is 3, the same as before the delete. The rotation absorbed the shrink, so the caller sees no change and no ancestor would need further rotations.
Cost
Each rebalance call does constant work: one height update, one balance check, and at most two rotations. The recursion visits one node per level, and the height is O(log n) (the next chapter proves this). Deletion therefore runs in O(log n) time. The number of rotations in the worst case is also O(log n), because a rotation can happen at every level on the path. Insertion performs at most two rotations in total.
In practice, cascading rotations are uncommon. Each one needs a very specific, nearly Fibonacci-shaped tree. A random workload usually performs a small constant number of rotations per delete. The O(log n) bound still matters when you reason about worst-case latency.
Edge cases and gotchas
- Copying the successor's key. The two-child case overwrites
n.keyand removes a different node. If outside code holds references to individual nodes, such as iterators, they can point at the wrong key or at a removed node. Relink the successor node itself if node identity matters. - Predecessor or successor. Either works. Using the successor every time can skew shapes slightly over many deletes. Alternating, or choosing the side from the taller subtree, spreads the effect.
- Deleting a missing key. The code reaches
None, returns it, and rebalances the ancestors. Nothing changes, but the path is still walked. Add a membership check first if you want to skip that work. - Stale heights. Every node on the return path must have its height updated before its balance factor is read.
rebalancecallsupdatefirst. Skipping that step is the most common cause of trees that look balanced but are not. - Rotation order. Both rotations update the lower node first, then the new root. Reversing the order reads a stale child height.
Testing deletion
Deletion bugs show up only for particular tree shapes. Check the invariants after every operation, as the randomized test does. check_avl recomputes heights from scratch instead of trusting the stored height fields, so it catches stale values as well as imbalance. Use a fixed random seed so a failing run can be reproduced.
Exercise
A node has balance factor +2 after a deletion in its right subtree. Its left child has balance factor 0. Which rotation fixes it, and does the height of the subtree rooted at this node shrink after the fix?
Show answer
A single right rotation at the node. The left child has two subtrees of equal height h+1, and the right side has height h. After the rotation the old left child becomes the root, with the old node as its right child. The new root's left subtree has height h+1 and its right subtree has height h+2, so the new root has height h+3, which equals the subtree's height before the deletion. The height does not shrink, so no ancestor above sees a change and the rebalancing can stop there.
Exercise
In the worked example, suppose you delete 3 and then 5 from the tree built from 2, 1, 4, 3, 5, in that order, without deleting 1. What is the tree after each deletion, and is any rotation needed?
Show answer
After deleting 3, node 4 has only a right child 5, with balance factor -1, and the root 2 has balance factor -1. No rotation is needed. After deleting 5, node 4 is a leaf, so root 2 has left child 1 and right child 4, both leaves, and the balance factor is 0. No rotation is needed in either step.