Data structures
Red-Black Tree
Start with the search problem
A binary search tree is useful because it turns ordered data into a decision process. At each node, the value is either equal, smaller, or larger. If the tree is balanced, one comparison removes about half of the remaining possibilities.
That is the whole reason logarithms appear here. O(log n) does not mean magic speed. It means the remaining work shrinks by a constant factor each step. With 31 sorted keys, a balanced shape needs only about five levels to decide where a value is.
Before red-black trees
Why balanced BST search is logarithmic
A balanced binary search tree puts a middle-ish value near the root. Each comparison keeps one side and discards the other side, so the remaining search space keeps shrinking by about half.
BST rule
A binary search tree stores each node with at most two children. The left child contains smaller values. The right child contains larger values. That single ordering rule lets search make a decision at every node.
If you are looking for 22 and you stand at 16, you do not inspect the left side at all. 22 is larger, so the only useful direction is right.
Why this tree exists
A normal binary search tree is only fast when it stays balanced. If values arrive in sorted order, the tree can collapse into a linked list, and search moves from logarithmic time toward linear time.
A red-black tree is a binary search tree with a small amount of color metadata. The colors do not store application data. They are a bookkeeping trick that keeps the tree approximately balanced while allowing insert and search to remain efficient.
Visual aid 1
Why ordinary BSTs can fail
First add items randomly and search. Then add items in sorted order and search again. Same BST rule, very different shape.
Random insertion
Usually gives the tree some left and right branching, so search visits fewer nodes.
inserted: 42, 18, 64
64 found through 42 -> 64. This behaves like logarithmic search.
Sorted insertion
Always goes to the right, so the tree turns into a linked list.
inserted: 5, 10, 15
15 found through 5 -> 10 -> 15. This is a chain, so worst-case search is O(n).
The failure mode
The sorted insertion example is the important warning. A binary search tree does not automatically balance itself. If every new value is larger than the previous value, each insert walks right, attaches a new right child, and creates a long chain.
Searching that chain is no better than scanning a linked list. The reader can see this by searching for the last sorted value: the search path visits almost every node, so the behavior becomes O(n) instead of O(log n).
Visual aid 2
How red-black repair keeps it shallow
Now insert values, including sorted values. The tree uses red/black colors, recoloring, and rotations to avoid the right-spine failure.
Repair log
- Insert 1 as red.
- Recolor parent 5, uncle 15, and grandparent 10.
- Force the root black.
Search result
25 found through path 20 -> 30 -> 25.
The red nodes are allowed to add flexibility, but a red node cannot have a red child. The black-height rule prevents one side from becoming a long chain.
Rotation playground
Rotate locally, keep order globally
Rotations look like a tree reshuffle, but the sorted inorder list stays exactly the same. That is why red-black trees can repair height without breaking binary-search ordering.
Before
20 has a right child 30. A left rotation can move 30 upward.
Sorted order check
Inorder remains 10 -> 20 -> 25 -> 30. Since the order is unchanged, search still works after the repair.
Black height counter
Count black nodes on every path
Black height is the pressure gauge of a red-black tree. If one path has more black nodes than another, the tree is no longer evenly constrained.
All root-to-NIL paths have the same black height, so this rule is satisfied.
Recolor vs rotate quiz
Pick the repair move
Red-black insertion has a small decision tree: red uncle means recolor; black uncle means rotate, sometimes with a prep rotation.
Parent is red and uncle is red
The new node has a red parent, but the uncle is also red. The tree can fix this without changing shape.
The rules
Red-black trees use five rules. The root is black. Every node is red or black. Every missing child, usually called a NIL leaf, is treated as black. A red node cannot have a red child. Finally, every path from a node down to its NIL leaves must contain the same number of black nodes.
Those rules are enough to prevent one side of the tree from growing wildly taller than the other. The tree is not perfectly balanced, but it is balanced enough that lookup, insertion, and deletion stay bounded by O(log n).
Insertion intuition
New values are inserted like a regular binary search tree node, and the new node starts red. Starting red is less disruptive because it does not immediately change the black count on every path.
The problem appears when the new red node has a red parent. That creates a red-red violation. The fix depends on the uncle node. If the uncle is red, the tree recolors parent and uncle black, pushes red upward to the grandparent, and checks again higher in the tree. If the uncle is black, the tree rotates around the grandparent and recolors the parent/grandparent pair.
Rotations
A rotation is a local pointer change that preserves sorted order. A left rotation moves a right child up. A right rotation moves a left child up. The inorder sequence is unchanged, which means the binary search tree property remains intact.
before:
x.right = y
y.left = b
after left rotate at x:
y.left = x
x.right = bRotations are why a red-black tree can repair itself without moving every node. Most fixes touch only a small neighborhood: node, parent, uncle, and grandparent.
Black height
Black height is the count of black nodes on any path from a node to a NIL leaf. The important part is equality: from the same starting node, every downward path must have the same black height.
This does not mean every path has the same total number of nodes. Red nodes can appear between black nodes, but because red nodes cannot be adjacent, the longest path cannot be more than about twice as long as the shortest path.
Where it shows up
Red-black trees are useful when the workload needs ordered keys, predictable worst-case behavior, and fast updates. They are common in systems code, language runtimes, schedulers, memory managers, and map/set implementations.
They are not always the best answer. Hash tables are often faster for direct lookup, B-trees are better for disk and page-oriented storage, and arrays can win when the data is small and cache locality dominates. A red-black tree shines when order and stable logarithmic updates matter at the same time.
Summary
- Colors: metadata used to enforce balance rules.
- Recoloring: moves a violation upward when parent and uncle are both red.
- Rotations: local pointer changes that preserve sorted order while repairing shape.
- Guarantee: search, insert, and delete remain O(log n) because the tree height stays bounded.