Sub topic 1
Balanced Trees: AVL and Red-Black Trees
Prerequisites
This chapter assumes that you know binary search tree (BST) search, insertion, and deletion; recursion; tree terms such as root, leaf, and subtree; and the difference between O(log n) and O(n) time.
Quick review: the binary search tree invariant
A binary search tree stores keys so that, for every node:
- Every key in the left subtree is smaller.
- Every key in the right subtree is larger.
- Each subtree follows the same rule.
This ordering invariant makes search efficient when the tree is short. Search compares the target with the current key, then follows only one child.
Why balance matters: height controls cost
The cost of a tree operation depends on its height, h, because one path from the root may contain h nodes.
| Tree shape | Height | Search, insert, delete |
|---|---|---|
| Balanced | `O(log n)` | `O(log n)` |
| Degenerate chain | `O(n)` | `O(n)` |
For example, inserting sorted keys into an ordinary BST creates a chain. Each new key becomes the right child of the previous key. The ordering invariant still holds, but the tree has lost its performance advantage.
Balanced trees add rules and repair operations to keep the height small.
Rotations: changing shape without breaking order
A rotation changes parent-child links while preserving in-order traversal. In-order traversal visits keys from smallest to largest, so preserving it preserves the BST invariant.
A right rotation around y moves its left child x upward. The subtree between x and y becomes y’s left subtree.
def rotate_right(y):
x = y.left
y.left = x.right
x.right = y
return x # new root of this subtreeA left rotation is the mirror operation: it moves the right child upward. After either rotation, callers must replace their pointer with the returned subtree root.
AVL trees: heights that differ by at most one
An AVL tree is a BST where each node’s left and right subtree heights differ by at most one. Its balance factor is:
height(left) - height(right)
Therefore, every balance factor must be -1, 0, or 1. Insertions and deletions may violate this rule. AVL repair uses rotations to restore it while keeping the BST ordering.
Exercise
Why can a BST have correct ordering but still require O(n) search time?
Show answer
Ordering controls which branch to follow, but it does not limit the tree’s height. Sorted insertion can create a chain of n nodes.