Sub topic 2
AVL Insertion and the Four Imbalance Cases
This chapter assumes you know binary search tree (BST) insertion and deletion, recursion, tree height, and the difference between O(log n) and O(n).
AVL insertion
An AVL tree is a BST where the heights of a node's left and right subtrees differ by at most one. Its balance factor is:
height(left) - height(right)
After inserting like a normal BST, update heights while returning toward the root. If a balance factor becomes 2 or -2, rotate.
| Case | Shape | Repair |
|---|---|---|
| Left-left | inserted into left child’s left subtree | Rotate right |
| Right-right | inserted into right child’s right subtree | Rotate left |
| Left-right | inserted into left child’s right subtree | Rotate left child left, then rotate node right |
| Right-left | inserted into right child’s left subtree | Rotate right child right, then rotate node left |
def rebalance(n):
update(n)
bf = balance_factor(n)
if bf > 1:
if balance_factor(n.left) < 0:
n.left = rotate_left(n.left) # left-right
return rotate_right(n) # left-left
if bf < -1:
if balance_factor(n.right) > 0:
n.right = rotate_right(n.right) # right-left
return rotate_left(n) # right-right
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)AVL deletion and rebalancing on the way up
Deletion first follows normal BST rules. A node with two children is replaced by its in-order successor. Then every ancestor on the return path is rebalanced. Unlike insertion, deletion can reduce a subtree's height and cause several ancestors to become unbalanced.
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)Why AVL trees have logarithmic height
The sparsest AVL tree of height h has subtree heights h - 1 and h - 2:
N(h) = N(h - 1) + N(h - 2) + 1
This Fibonacci-like growth means the height is O(log n). Search, insertion, and deletion therefore take O(log n).
Red-black trees: the color rules
A red-black tree uses a color on each node instead of requiring AVL-level balance. Its five rules are:
- Every node is red or black.
- The root is black.
- Every missing child, treated as a leaf, is black.
- A red node cannot have a red child.
- Every path from a node to missing leaves has the same number of black nodes.
These rules allow more height than AVL trees but usually require less rebalancing during updates.
Exercise
In which AVL case do you rotate the child first, and why?
Show answer
In a left-right or right-left case. The child rotation converts the inner shape into an outer case, which a second rotation fixes.