COMPUTER ENGINEER

← BlogDATA STRUCTURES / ALGORITHMSPython example pack ↓

Trees and indexes · 19 / 53

AVL and red-black: preserving balance

Understand → trace → implement → justify

1 min reading · allow extra time for practice

AVL keeps each node's left/right height difference within1. Update affected ancestors after insertion, using single LL/RR or double LR/RL rotations. Rotations preserve inorder key order while changing shape. Deletion may require balancing at several ancestors.

Red-black trees bound height using colour rules: black root, no red-red parent-child pair, and equal black height to NIL leaves. These support height≤2log₂(n+1). NIL represents mathematical missing-child leaves, implemented through sentinels or null handling.

AVL has stricter balance; red-black has different update constants. Neither is universally faster. Educational implementations must maintain parent/root links and augmented metadata, while production use should usually rely on tested libraries.

A worked trace

Insert30,20,10:30 becomes left-heavy. A right rotation yields root20 with children10 and30, preserving inorder10,20,30.

Cost and assumptions

Balanced search/insert/delete O(log n). Local rotations O(1); metadata updates along the path O(log n).

Executable example

Run with Python 3. Assertions check a small example; they do not constitute a general correctness proof. Some advanced examples are explicitly small models or reference oracles, not full production implementations.

Python 3
# Right rotation in tuple form: (key, left, right).
def rotate_right(y):
    ykey, x, right = y
    if x is None: raise ValueError("missing pivot")
    xkey, left, middle = x
    return (xkey, left, (ykey, middle, right))
assert rotate_right((30,(20,(10,None,None),None),None))[0] == 20

TEST YOUR UNDERSTANDING

Your turn

What breaks if subtree sizes are left unchanged after a rotation?

Reveal the reasoning

Key search may remain correct while rank/select becomes wrong. Balance and augmentation need separate verification.

Take it further

  1. Write down the input contract and the invariant before changing the example.
  2. Add empty, boundary, duplicate and adversarial cases where they are relevant. Compare with a simple oracle.
  3. Derive the cost under the stated model; measure several input sizes and explain discrepancies.

Primary reading & lecture notes

Original explanations in this course; these references provide proofs and further reading. Source links may cover the broader module.

MIT 6.006 · Introduction to Algorithms ↗Pat Morin · Open Data Structures ↗
Solve the exercise before moving on.