Balanced Trees: AVL, Red-Black & B-Trees
Rotations and invariants that guarantee O(log n) height.
A plain BST is only as good as its insertion order, and real data arrives sorted all the time. Balanced trees refuse to rely on luck. They keep an invariant (sibling subtrees within one level of each other, or the same number of black nodes on every path) and repair it with rotations after each update. The reward is a worst-case guarantee: height on every input, so a million keys never cost more than a few dozen comparisons.
What you’ll learn
- Prove that a rotation preserves the BST property, takes time and changes depths only locally.
- Derive the AVL height bound from Fibonacci trees, and rebalance an AVL tree with the four rotation cases.
- State the red-black properties, prove , and compare AVL and red-black trees by height and by rotations per update.
- Explain why databases use B-trees and B+ trees, and choose between the library's ordered map, a hash map, a heap and a hand-written balanced tree.
Rotations: the one move
A balanced tree fights back against bad insertion orders with one local move, the rotation, applied after each update to restore an invariant that caps the height at in the worst case. Rotating right at lifts its left child : 's right subtree becomes 's left subtree, and becomes 's right child. Rotating left at undoes it. Only three child pointers change, so a rotation takes time.
Think first In a right rotation at , which of the subtrees , , changes its parent?
Only , which moves from (as its right subtree) to (as its left subtree). stays under and under . The three child pointers that change are 's right, 's left, and the pointer from 's old parent, which now points to .
AVL trees: siblings within one level
Let be the fewest nodes in an AVL tree of height . A smallest one has subtrees of heights and , each as small as possible:
Adding 1 to both sides gives the Fibonacci recurrence, so with :
With , the golden ratio, . An AVL tree with nodes and height therefore has :
In base 2, using and :
The trees that achieve , called Fibonacci trees, are the tallest AVL trees of their size.
Insertion. Insert as in a plain BST, then walk back up updating heights. At the first ancestor whose balance factor reaches , one of four configurations arises, named by the two steps from toward the new key. LL and RR are fixed by a single rotation at ; LR and RL by a double rotation, first at 's child, then at . The repaired subtree has exactly the height it had before the insertion, so nothing above changes: at most one single or double rotation per insertion.
Deletion. A repair can shorten the subtree, which may unbalance the next ancestor up, so a deletion may rotate at nodes on the way to the root; alternating insertions and deletions can even force rotations per deletion again and again (Amani, Lai & Tarjan, 2015).
class Node:
def __init__(self, key):
self.key, self.left, self.right, self.h = key, None, None, 0
def h(x): return x.h if x else -1 # height in edges; empty tree -1
def fix(x): x.h = 1 + max(h(x.left), h(x.right)); return x
def bf(x): return h(x.left) - h(x.right) # balance factor
def rotate_right(y): # y's left child x comes up
x = y.left
y.left, x.right = x.right, y
fix(y); return fix(x)
def rotate_left(x): # x's right child y comes up
y = x.right
x.right, y.left = y.left, x
fix(x); return fix(y)
def rebalance(x):
fix(x)
if bf(x) == 2: # left side too tall
if bf(x.left) < 0: x.left = rotate_left(x.left) # LR: double
return rotate_right(x) # LL: single
if bf(x) == -2: # right side too tall
if bf(x.right) > 0: x.right = rotate_right(x.right) # RL: double
return rotate_left(x) # RR: single
return x
def insert(x, key):
if x is None: return Node(key)
if key < x.key: x.left = insert(x.left, key)
elif key > x.key: x.right = insert(x.right, key)
return rebalance(x)Recursive AVL insertion: rebalance runs at every ancestor on the way back up, but only the first unbalanced one rotates. Tested on random and sorted inputs, checking the balance factors and the inorder sequence; inserting in order gives a perfect tree of height 9.
Think first Insert 10, 30, 20 into an empty AVL tree. Which repair happens?
At 10 the balance factor becomes , and the new key 20 lies to the right and then to the left of 10: the RL case. Rotate right at 30, then left at 10, and 20 becomes the root with children 10 and 30.
What is the greatest possible height of an AVL tree with keys? (Heights count edges; a complete tree with keys has height 19.)
Show the answer
27
, so the tallest AVL tree with a million keys has height 27, about , just under the bound . A red-black tree with a million keys can reach height 36, and a plain BST .
Red-black trees: one bit of color
Black height. Let count the black nodes on any path from down to a NIL, the NIL included but not itself. By induction on the height of , its subtree holds at least keys, since each child has black height at least :
At least half black. Let be the number of edges on the longest path from the root down to a NIL. Red nodes are never adjacent and the NIL is black, so at least half of the nodes below the root on that path are black:
Solve for . The height counted between keys, , is smaller still (CLRS, Lemma 13.1):
Insertion colors the new node red, which changes no black height, and repairs a red node with a red parent in one of three cases: if the new node's uncle is red, recolor and continue two levels up; otherwise one or two rotations finish the job. A red-black tree makes at most 2 rotations per insertion and at most 3 per deletion. Recoloring can climb levels in the worst case, but it is amortized (Tarjan, 1983). The cases, and why each one is a 2-3-4-tree operation in disguise, are the subject of the Optimal lesson Red-Black Trees & 2-3-4 Trees.
Think first Why is a newly inserted node colored red rather than black?
A black node would add one to the black count of every path through it, breaking rule 3 all the way up to the root. A red node changes no black count; it can only produce a red node with a red parent, a local violation that recoloring and rotations repair.
| Property | AVL tree | Red-black tree |
|---|---|---|
| Invariant | at every node | No red node has a red child; equal black counts on all paths |
| Height bound | ||
| Tallest with | 27 | 36 |
| Rotations per insertion | At most one single or double | At most 2 |
| Rotations per deletion | At most 3 | |
| Extra data per node | A height or a balance factor (2 bits) | 1 color bit |
| Typical use | Lookup-heavy workloads | std::map and std::set (libstdc++, libc++, MSVC), Java's TreeMap, the Linux kernel's rbtree |
B-trees: wide nodes for slow memory
Everything so far counts comparisons. On disk, and even in RAM, that is the wrong cost: an SSD reads a block of several kilobytes at a time, and a CPU fetches 64-byte cache lines. A balanced binary tree with a billion keys has about 30 levels, and every level can cost a separate block read. A B-tree (Bayer & McCreight, 1972) packs many keys into each node instead, so that one node fills one block.
A search reads one node per level and does the comparisons inside it in fast memory. An insertion that overfills a node splits it around its median key, which moves up into the parent; CLRS splits every full node it passes on the way down, so a parent always has room, and the tree grows only when the root splits, which keeps all leaves at the same depth. A deletion borrows a key from a sibling, or merges with one, to keep every node at least keys full.
A B-tree with minimum degree (every node except the root holds 499 to 999 keys) stores keys. How many nodes does a search read, root included?
Show the answer
4
The height is at most , and it cannot be 2, because three levels of nodes with at most 1,000 children each hold at most keys. So the height is exactly 3: four levels, four node reads. In practice the top levels stay in RAM, leaving one or two disk reads, where a balanced binary tree would need about 30.
A B+ tree keeps all records in the leaves and only separator keys in the internal nodes, which raises the fan-out, and it links the leaves in key order, so a range query descends once and then reads consecutive leaves. Relational databases such as InnoDB, PostgreSQL and SQLite index with B+ tree variants, as do many file systems. In memory, B-trees win on cache lines too: Rust's standard BTreeMap and Abseil's btree_map for C++ are B-trees, and Linux tracks each process's virtual memory areas in the maple tree, a B-tree variant for ranges. The Optimal lesson B-Trees & B+ Trees proves the I/O bounds.
Recognizing it
Reach for a balanced tree, almost always the library's, when:
- you need order and guaranteed on inputs you do not control: sorted insertions, timestamps, adversarial tests;
- elements leave from the middle while you keep asking for the minimum, maximum, floor or ceiling: a multiset;
- each request gets the best-fitting resource, the smallest capacity its demand, which is then removed;
- the data lives on disk or does not fit in memory: a B-tree or B+ tree.
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| The median of every window of consecutive values | Two multisets, the lower and the upper half, rebalanced after each step | |
| The skyline of overlapping rectangles | Sweep the -events; a multiset of active heights gives the current maximum; erase one copy when a rectangle ends | |
| Give each job the smallest free machine whose capacity is at least its demand | lower_bound in a multiset of capacities, then erase that copy | |
| The -th smallest value under insertions and deletions | An order-statistic tree, or offline a Fenwick tree over compressed values | per operation |
| Index a billion rows by key, with range scans | A B+ tree with block-sized nodes | block reads |
#include <iterator>
#include <set>
#include <vector>
using namespace std;
// Median of every window of length k, in O(n log k)
vector<double> windowMedians(const vector<int>& a, int k) {
multiset<int> lo, hi; // lo: smaller half, |lo| = |hi| or |hi| + 1
vector<double> out;
for (int i = 0; i < (int)a.size(); ++i) {
if (lo.empty() || a[i] <= *lo.rbegin()) lo.insert(a[i]); else hi.insert(a[i]);
if (i >= k) { // erase ONE copy of the value leaving
auto it = lo.find(a[i - k]);
if (it != lo.end()) lo.erase(it); else hi.erase(hi.find(a[i - k]));
}
while (lo.size() > hi.size() + 1) { hi.insert(*lo.rbegin()); lo.erase(prev(lo.end())); }
while (hi.size() > lo.size()) { lo.insert(*hi.begin()); hi.erase(hi.begin()); }
if (i >= k - 1)
out.push_back(k % 2 ? *lo.rbegin() : (*lo.rbegin() + (double)*hi.begin()) / 2);
}
return out;
}Every element of lo is at most every element of hi, so the median is the largest element of lo (or the average of the two middle values when is even). Erasing by iterator removes one copy; erase(value) would remove them all. Tested against sorting every window.
operations arrive: insert a value, delete one copy of an arbitrary value , report the current maximum. Which choice is the most direct?
- A
std::priority_queuealone - A
std::multiset:insert,erase(find(x))and*rbegin() - An
unordered_multiset - A sorted
std::vector
Show the answer
B. A std::multiset: insert, erase(find(x)) and *rbegin()
A balanced BST that keeps duplicates does all three in : insertion, erasing one iterator, and reading the last element.
Key takeaways
- A rotation changes three child pointers in time, keeps the inorder sequence (and so the BST property), and moves one subtree up a level and another down.
- AVL trees keep sibling heights within one: minimum sizes are Fibonacci numbers, so ; an insertion needs at most one single or double rotation, a deletion up to .
- Red-black trees forbid red-red edges and equalize black counts: , at most 2 rotations per insertion and 3 per deletion, and amortized recolorings. They are the usual library choice.
- B-trees keep all leaves at one depth with nodes of to keys, so and a billion keys fit in four levels; B+ trees keep the records in linked leaves for range scans.
- Use the library's ordered map or multiset; write your own balanced tree only to augment it or to split and join it.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
After an AVL insertion, the first unbalanced ancestor is repaired with one single or double rotation. Why does nothing above need repair?
- The repaired subtree is back to its height before the insertion, so no ancestor's balance factor changes
- The root of an AVL tree is always balanced
- Heights of nodes above are not stored
- AVL trees tolerate balance factors of above the first repair
Show the answer
A. The repaired subtree is back to its height before the insertion, so no ancestor's balance factor changes
The insertion raised the height of 's taller side by one; the single or double rotation lowers it by one again. Every ancestor of sees its subtree heights exactly as before the insertion, so their balance factors are unchanged.
Which comparison between AVL trees and red-black trees is correct?
- Red-black trees guarantee height at most about
- AVL trees are never taller than about , while red-black deletions need at most 3 rotations against AVL's
- AVL trees need fewer rotations per deletion than red-black trees
- Red-black trees store each node's height
Show the answer
B. AVL trees are never taller than about , while red-black deletions need at most 3 rotations against AVL's
The AVL invariant is stricter, so AVL trees are shorter ( against ), but it is also costlier to restore after a deletion, which may rotate at every level, whereas a red-black deletion rotates at most 3 times.
Why do databases index with B+ trees rather than red-black trees?
- Each node visit can cost a block read, and wide nodes cut the height for a billion keys from about 30 levels to 3 or 4, while linked leaves make range scans sequential
- B+ trees make fewer key comparisons than red-black trees
- Red-black trees cannot store string keys
- B+ trees never need any rebalancing
Show the answer
A. Each node visit can cost a block read, and wide nodes cut the height for a billion keys from about 30 levels to 3 or 4, while linked leaves make range scans sequential
The cost that matters on disk is the number of blocks read, not the number of comparisons. A node with hundreds of keys fills a block, so a search reads blocks, a factor of about fewer than a binary tree.
A right rotation at , whose left child is , changes which of these?
- The inorder sequence of the keys
- The set of keys in the tree
- The depths of the nodes in two of the subtrees, and the parent of the middle one
- The height of every node in the tree
Show the answer
C. The depths of the nodes in two of the subtrees, and the parent of the middle one
Subtree moves up a level, moves down a level, and changes parent from to at the same depth. The inorder sequence, and hence the BST property, is unchanged; heights change only at , and their ancestors.
Go deeper
- Red-Black Trees & 2-3-4 Trees · The correspondence, insertion and deletion cases, and left-leaning variants.
- B-Trees & B+ Trees · Wide nodes for disks and databases.
- The Balanced-Tree Zoo · AVL, WAVL, weight-balanced and scapegoat trees: which invariant buys what.
Further reading
- G. M. Adel'son-Vel'skii & E. M. Landis, "An algorithm for the organization of information," Soviet Mathematics Doklady 3 (1962), 1259–1262.
- L. J. Guibas & R. Sedgewick, "A dichromatic framework for balanced trees," Proceedings of the 19th IEEE Symposium on Foundations of Computer Science (1978), 8–21.
- R. Bayer & E. McCreight, "Organization and maintenance of large ordered indexes," Acta Informatica 1 (1972), 173–189.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 13 and 18.