24. Red-Black Trees
Self-balancing BSTs that power your standard library
A binary search tree gives you O(log n) lookups — if it stays balanced. But insert elements in sorted order and the tree degenerates into a linked list, with O(n) lookups. The fix: make the tree self-balancing, automatically restructuring itself after every insertion and deletion to guarantee O(log n) height.
Red-black trees are the most widely deployed self-balancing BST in practice. Java's TreeMap, C++'s std::map, and Linux's CFS scheduler all use them. The rules seem arcane at first — coloring nodes red or black, rotating subtrees — but they encode a simple invariant: no path from root to leaf is more than twice as long as any other.
The Problem
A plain binary search tree (BST) supports insert, delete, and search in O(h) time, where h is the tree's height. In the best case, h = O(log n). In the worst case (sorted input), h = O(n). We need a BST that guarantees h = O(log n) regardless of insertion order.
The Five Rules
A red-black tree is a BST where every node is colored red or black, and the following five properties hold:
Red-Black Properties
- Every node is red or black
- The root is black
- Every null leaf (NIL) is black — we treat missing children as black sentinel nodes
- Red nodes cannot have red children — if a node is red, both its children must be black (no two consecutive reds on any path)
- Black-height invariant: every path from a given node to any of its descendant NIL leaves passes through the same number of black nodes
Property 5 is the key one. The black-height of a node is the number of black nodes on any path from it to a NIL leaf (not counting itself). The black-height invariant, combined with property 4, guarantees that the longest path (alternating red-black) is at most twice the shortest path (all black).
Why this guarantees O(log n) height
Shortest root-to-leaf path: all black nodes
Longest root-to-leaf path: alternating red and black
If black-height = k:
shortest path length = k
longest path length = 2k (red-black-red-black-...)
A tree with n internal nodes has height h ≤ 2 log₂(n+1).
So all operations are O(log n).
A Red-Black Tree Example
A valid red-black tree
[13B]
/ \
[8R] [17R]
/ \ \
[1B] [11B] [25B]
\ /
[6R] [22R]
B = black, R = red
Black-height of root = 2 (every root-to-NIL path has 2 black nodes below root)
Verify property 4: no red node has a red child ✓
Verify property 5: count black nodes on each root-to-NIL path:
13→8→1→NIL : black nodes below root = 1(black) + NIL = 2 (8 is red, skipped)
13→8→1→6→NIL : 1(black) + NIL = 2 (8 red, 6 red, 1 black)
13→8→11→NIL : 11(black) + NIL = 2 (8 is red)
13→17→25→22→NIL: 25(black) + NIL = 2 (17 red, 22 red)
13→17→25→NIL : 25(black) + NIL = 2
All paths: 2 black nodes below root ✓
Rotations
When an insertion or deletion violates the red-black properties, we fix it with rotations — local restructurings that preserve the BST ordering while changing the tree's shape.
Left rotation on node x
Before: After:
x y
/ \ / \
a y x c
/ \ / \
b c a b
y was x's right child; now x is y's left child.
The subtree b moves from y's left to x's right.
BST property preserved: a < x < b < y < c
Right rotation on node y
Before: After:
y x
/ \ / \
x c a y
/ \ / \
a b b c
The exact mirror of left rotation.
Rotations run in O(1) time — they only change a constant number of pointers.
Insertion
Insertion into a red-black tree starts like any BST insertion: find the correct position and insert the new node. The new node is always colored red (because adding a red node doesn't change any path's black-height). This might violate property 4 (no red-red parent-child), so we fix up.
-
BST insert and color red
Insert the new node at the correct BST position. Color it red.
-
Fix violations
If the new node's parent is black, we're done — no violation. If the parent is red, we have a red-red violation. The fix depends on the uncle (the parent's sibling).
Insertion Cases
Case 1: Uncle is red
Recolor: make parent and uncle black, grandparent red. Then move up to the grandparent and check again (it might now violate with its parent).
[G:B] [G:R] ← might violate with G's parent
/ \ / \
[P:R] [U:R] → [P:B] [U:B]
/ /
[N:R] [N:R]
Case 2: Uncle is black, node is "inner" child
The new node is between its parent and grandparent (e.g., right child of a left parent). Rotate the parent to convert this into Case 3.
[G:B] [G:B]
/ \ / \
[P:R] [U:B] → [N:R] [U:B]
\ /
[N:R] [P:R]
(Left-rotate P) → now it's Case 3
Case 3: Uncle is black, node is "outer" child
Rotate the grandparent and swap colors of parent and grandparent. Done.
[G:B] [P:B]
/ \ / \
[P:R] [U:B] → [N:R] [G:R]
/ \
[N:R] [U:B]
(Right-rotate G, swap colors P↔G)
The fix-up walks at most O(log n) levels up the tree (Case 1 propagates upward), and Cases 2 and 3 terminate with at most 2 rotations. So insertion is O(log n) total.
Insertion Worked Example
Insert 4 into the tree [2B, 1R, 7R, 5B, 8B]
Starting tree:
[2B]
/ \
[1B] [7R]
/ \
[5B] [8B]
BST insert 4 (as red) under 5:
[2B]
/
[1B] [7R]
/
[5B] [8B]
/
[4R]
Check: parent 5 is black → no violation! Done.
Now insert 3 (as red) under 4:
[2B]
/
[1B] [7R]
/
[5B] [8B]
/
[4R]
/
[3R] ← red-red violation! (4 is red, 3 is red)
Parent = 4 (red), Uncle = NIL (black) → Case 3
4 is left child of 5, 3 is left child of 4 → outer child
Right-rotate 5, swap colors 4↔5:
[2B]
/
[1B] [7R]
/
[4B] [8B]
/
[3R] [5R]
All properties restored ✓
Deletion
Deletion is more complex than insertion — it can require up to 3 rotations and several recolorings. The basic idea:
- Perform standard BST deletion (find the node, replace with successor if needed)
- If the deleted node (or its replacement) was red, we're fine — no properties violated
- If it was black, we've reduced the black-height on one path, creating a "double-black" node that needs fixing
The fix-up cases for deletion are the mirror of insertion: they examine the sibling of the double-black node and its children's colors, applying rotations and recolorings to restore balance. There are 4 cases (and their mirrors), but the key insight is the same: at most O(log n) recolorings and at most 3 rotations.
Deletion Complexity
Deletion performs the BST delete in O(log n), then at most 3 rotations and O(log n) recolorings to restore the red-black properties. Total: O(log n).
Red-Black Trees vs. AVL Trees
| Property | Red-Black Tree | AVL Tree |
|---|---|---|
| Balance criterion | Black-height + no red-red | Height difference ≤ 1 at every node |
| Height bound | ≤ 2 log₂(n+1) | ≤ 1.44 log₂(n+2) |
| Search | Slightly slower (taller) | Slightly faster (shorter) |
| Insert | ≤ 2 rotations | ≤ 2 rotations |
| Delete | ≤ 3 rotations | O(log n) rotations |
| Best for | Insert/delete-heavy workloads | Search-heavy workloads |
Red-black trees do fewer rotations on deletion — at most 3 vs. potentially O(log n) for AVL. This makes them the preferred choice for general-purpose use, especially in standard library implementations where insert and delete are frequent.
Complexity Summary
| Operation | Time |
|---|---|
| Search | O(log n) |
| Insert | O(log n) — at most 2 rotations |
| Delete | O(log n) — at most 3 rotations |
| Space | O(n) — one color bit per node |
The 2-3-4 Tree Connection
Red-black trees are isomorphic to 2-3-4 trees (a type of B-tree). Every 2-3-4 tree can be converted to a red-black tree and vice versa:
- A 2-node (one key, two children) is a black node
- A 3-node (two keys, three children) is a black node with one red child
- A 4-node (three keys, four children) is a black node with two red children
This correspondence explains why the red-black rules work: they're encoding the perfectly balanced structure of a 2-3-4 tree in a binary tree format. If you've read the B-Trees article, this connection should click immediately.
Where Red-Black Trees Are Used
| Application | Implementation |
|---|---|
| Java | TreeMap, TreeSet, HashMap (collision chains since Java 8) |
| C++ STL | std::map, std::set, std::multimap, std::multiset |
| Linux kernel | CFS scheduler (task timeline), memory management (vm_area_struct) |
| Nginx | Timer event management |
| .NET | SortedDictionary<K,V>, SortedSet<T> |
Key Takeaways
- Red-black trees are self-balancing BSTs that guarantee O(log n) height via coloring rules
- Five properties ensure no root-to-leaf path is more than twice as long as any other
- Rotations are O(1) local restructurings that preserve BST order while rebalancing
- Insertion colors the new node red, then fixes red-red violations with at most 2 rotations
- Deletion may require up to 3 rotations and O(log n) recolorings
- Compared to AVL trees: slightly taller but fewer rotations on delete — better for insert/delete-heavy workloads
- Red-black trees are isomorphic to 2-3-4 trees — the coloring rules encode B-tree balance in a binary format
- They're the most widely used balanced BST in practice: Java, C++, Linux kernel, and more
Try It Yourself — Red-Black Tree
Insert values one at a time and watch the tree rebalance. Red nodes and black nodes are color-coded. Rotations are animated so you can see exactly how the tree restructures. Try inserting sorted values to see how the tree stays balanced.
Red-black trees are a masterpiece of practical algorithm design. The rules seem arbitrary until you see the 2-3-4 tree hiding underneath — then it all clicks. The tree is always "almost balanced," never straying far from optimal height, and the fix-up procedure is bounded and predictable. That predictability — at most 3 rotations per delete, 2 per insert — is why they won the standard library war over AVL trees. If you want to go deeper into tree-based data structures, the B-Trees article covers the multi-way trees that red-black trees secretly encode, and the Trie article explores a completely different approach to tree-based search.