A red-black tree is a binary search tree in which every node is colored red or black, and a handful of coloring rules guarantee that no root-to-leaf path is more than twice as long as any other. That keeps the height below 2 log₂(n + 1), so search, insert and delete are O(log n) in the worst case. Its balance is looser than an AVL tree's, but repairs are cheaper (at most two rotations per insert and three per delete), which is why it powers Java's TreeMap, C++'s std::map and large parts of the Linux kernel.
Think of it like
Toll booths and bypasses
Imagine a road network where every route from the capital to any coastal town passes through exactly the same number of toll booths (black nodes). Between two booths you may take at most one free bypass (a red node), never two in a row. The shortest possible route is all booths; the longest alternates booth, bypass, booth, bypass. So no route can be more than twice as long as another, which is exactly the red-black height guarantee.
The five properties
- 1Every node is either red or black.
- 2The root is black.
- 3Every leaf (the
NILplaceholder hanging below the real nodes) is black. - 4A red node never has a red child: no two reds in a row on any path.
- 5For every node, all paths from it down to descendant
NILleaves contain the same number of black nodes.
- NIL leaf
- Textbooks draw explicit black leaves under every real node. In code they are simply
nullpointers that you treat as black (or a single shared sentinel node). - Black-height bh(x)
- The number of black nodes on any path from
xdown to a leaf, not countingxitself. Property 5 is what makes this well defined. - Uncle
- The sibling of a node's parent. During insertion its color decides between recoloring and rotating.
Why the height is at most 2 log₂(n + 1)
- 1
Black nodes force size
By induction, a subtree rooted at
xcontains at least2^bh(x) − 1real nodes: each child has black-height at leastbh(x) − 1, so the count at least doubles per black level. - 2
Red nodes are at most half
Property 4 means reds cannot be adjacent, so on any root-to-leaf path at least half the nodes are black. Hence
bh(root) ≥ h / 2. - 3
Combine
n ≥ 2^(h/2) − 1, which rearranges to the bound below.
Insertion
Insert the key exactly as in a Binary Search Trees and color the new node red. A red node adds no black nodes to any path, so property 5 still holds. The only rule that can break is property 4 (when the new node's parent is also red), or property 2 if the tree was empty. A fix-up loop repairs it, and the deciding question is always: what color is the uncle?
| Case | Situation | Action | Then |
|---|---|---|---|
| 1 | Uncle is red | Recolor: parent and uncle black, grandparent red | The grandparent may now clash with its parent; repeat from there |
| 2 | Uncle is black, node is an inner child (triangle) | Rotate the parent away from the node so the three form a line | Fall through to case 3 |
| 3 | Uncle is black, node is an outer child (line) | Rotate the grandparent the other way; swap colors of parent and grandparent | Done |
| End | Loop finished | Color the root black |
g(B) g(R) <- may clash with its own parent:
/ \ / \ continue the fix-up from g
p(R) u(R) ==> p(B) u(B)
/ /
z(R) z(R) g(B) g(B) z(B)
/ \ / \ / \
p(R) u(B) ==> z(R) u(B) ==> p(R) g(R)
\ / \
z(R) p(R) u(B)
left-rotate p right-rotate g, swap colorsA worked example
| Insert | Situation | Action | Tree afterward |
|---|---|---|---|
| 10 | Empty tree | Color the root black | 10B |
| 20 | Parent 10 is black | Nothing to fix | 10B (-, 20R) |
| 30 | Parent 20 red, uncle NIL (black), line | Left-rotate 10, swap colors | 20B (10R, 30R) |
| 15 | Parent 10 red, uncle 30 red | Recolor 10 and 30 black, 20 red; root back to black | 20B (10B (-, 15R), 30B) |
| 13 | Parent 15 red, uncle NIL (black), triangle | Right-rotate 15, left-rotate 10, recolor | 20B (13B (10R, 15R), 30B) |
Insertion performs at most two rotations. Case 1 recoloring can climb all the way to the root, so the worst case is O(log n) recolors, but amortized over a sequence of inserts it is O(1).
Deletion, in overview
Delete as in a BST. If the node that is physically removed was red, nothing breaks. If it was black, every path through that spot is now one black short. The child that takes its place is marked double black: it carries an extra unit of blackness that must be pushed up the tree or absorbed. The fix-up looks at that node's sibling:
| Case | Sibling situation | Action |
|---|---|---|
| 1 | Sibling is red | Rotate the parent toward the double-black node and swap the parent's and sibling's colors. The new sibling is black, so continue with cases 2 to 4. |
| 2 | Sibling black, both its children black | Color the sibling red and move the extra black up to the parent. If the parent was red, color it black and stop. |
| 3 | Sibling black, near child red, far child black | Rotate the sibling away from the double-black node and swap colors, turning it into case 4. |
| 4 | Sibling black, far child red | Rotate the parent toward the double-black node; the sibling takes the parent's color, and the parent and far child become black. Done. |
Red-black trees are 2-3-4 trees in disguise
Merge every red node into its black parent. Each black node plus its red children becomes a single node with 1, 2 or 3 keys: a 2-3-4 tree, which is a B-Trees & B+ Trees of order 4. Property 5 (equal black height) becomes "all leaves at the same depth", which is the defining property of B-trees.
| 2-3-4 tree node | Red-black encoding |
|---|---|
| 2-node (1 key, 2 children) | A black node with two black children |
| 3-node (2 keys, 3 children) | A black node with one red child, leaning left or right |
| 4-node (3 keys, 4 children) | A black node with two red children |
- Case 1 recoloring is splitting a full 4-node: the middle key (the grandparent) moves up into the parent node.
- Rotations do not change the 2-3-4 tree at all; they only change which key of a 3-node is drawn as the black one.
- The height bound follows: a 2-3-4 tree with n keys has at most log₂(n + 1) levels, and each level becomes at most two binary levels.
Left-leaning red-black trees
Robert Sedgewick's left-leaning red-black tree (LLRB, 2008) adds one restriction: red links may only lean left. The tree then corresponds one-to-one with a 2-3 tree, and insertion collapses into three local fixes applied on the way back up the recursion:
- 1
Right-leaning red link
If the right child is red and the left is not, rotate left.
- 2
Two reds in a row
If the left child and its left child are both red, rotate right.
- 3
Both children red
Flip colors: children turn black and the node turns red, passing the middle key up (a 4-node split).
Classic red-black (CLRS)
- Iterative fix-up with parent pointers
- At most 2 rotations per insert, 3 per delete
- What production libraries implement
Left-leaning red-black
- Recursive, about a third of the code
- Easy to derive and remember from 2-3 trees
- More rotations in practice; deletion is still fiddly
Where red-black trees run
| System | What the tree does |
|---|---|
Java TreeMap / TreeSet | The ordered map and set. HashMap also converts a bucket into a red-black tree once it grows past 8 entries, capping collision cost at O(log n). |
C++ std::map, std::set, std::multimap | The node-based ordered containers in libstdc++, libc++ and MSVC. |
| Linux CFS scheduler | Runnable tasks ordered by virtual runtime; the leftmost node (cached) is the next task to run. Its successor, EEVDF, also uses an augmented red-black tree. |
| Linux kernel, elsewhere | epoll's set of watched file descriptors and high-resolution timer queues. |
Complexity
| Operation | Time | Rotations | Notes |
|---|---|---|---|
| Search | O(log n) | 0 | Plain BST search; colors are ignored |
| Insert | O(log n) | ≤ 2 | Recoloring may climb O(log n) levels, O(1) amortized |
| Delete | O(log n) | ≤ 3 | Double-black fix-up |
| Min, max, floor, ceiling, successor | O(log n) | 0 | Same walks as any BST |
| Space | O(n) | One color bit per node (plus a parent pointer in classic code) |
Height is at most 2 log₂(n + 1), so every bound above is worst case.
Implementation
Iterative BST insert followed by the three-case fix-up, with parent pointers. Null children count as black leaves.
RED, BLACK = True, False
class Node:
def __init__(self, key, parent=None):
self.key = key
self.color = RED # new nodes start red
self.left = None
self.right = None
self.parent = parent
def is_red(n) -> bool:
return n is not None and n.color == RED # None leaves count as black
class RedBlackTree:
def __init__(self):
self.root = None
def search(self, key) -> bool:
n = self.root
while n:
if key == n.key:
return True
n = n.left if key < n.key else n.right
return False
def _rotate_left(self, x):
y = x.right
x.right = y.left
if y.left:
y.left.parent = x
y.parent = x.parent
if x.parent is None:
self.root = y
elif x is x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
def _rotate_right(self, y):
x = y.left
y.left = x.right
if x.right:
x.right.parent = y
x.parent = y.parent
if y.parent is None:
self.root = x
elif y is y.parent.right:
y.parent.right = x
else:
y.parent.left = x
x.right = y
y.parent = x
def insert(self, key) -> None:
parent, n = None, self.root
while n: # ordinary BST descent
if key == n.key:
return # no duplicates
parent = n
n = n.left if key < n.key else n.right
z = Node(key, parent)
if parent is None:
self.root = z
elif key < parent.key:
parent.left = z
else:
parent.right = z
self._fix_insert(z)
def _fix_insert(self, z) -> None:
while is_red(z.parent): # red parent: two reds in a row
p = z.parent
g = p.parent # exists and is black
if p is g.left:
u = g.right
if is_red(u): # case 1: red uncle, recolor
p.color = u.color = BLACK
g.color = RED
z = g # continue two levels up
else:
if z is p.right: # case 2: triangle -> line
self._rotate_left(p)
z, p = p, z
p.color = BLACK # case 3: line, rotate g
g.color = RED
self._rotate_right(g)
else: # mirror image
u = g.left
if is_red(u):
p.color = u.color = BLACK
g.color = RED
z = g
else:
if z is p.left:
self._rotate_right(p)
z, p = p, z
p.color = BLACK
g.color = RED
self._rotate_left(g)
self.root.color = BLACK # property 2Key takeaways
- Five coloring rules (especially no red-red and equal black height) guarantee height ≤ 2 log₂(n + 1).
- New nodes are red. On a red-red violation, the uncle decides: red uncle means recolor and climb; black uncle means one or two rotations and stop.
- Deletion pushes a "double black" up the tree using the sibling's colors, with at most three rotations.
- A red-black tree is a 2-3-4 tree drawn as a binary tree; recoloring is a node split, and LLRB trees mirror 2-3 trees.
- Compared with AVL trees they are a little taller but restructure less on updates, which makes them the default ordered map in Java, C++ and Linux.
Common pitfalls
- Reading the color of a null uncle or sibling: treat null as black (or use a shared black sentinel node).
- Forgetting to update parent pointers, or the root pointer, during a rotation in the classic implementation.
- Forgetting the final
root.color = BLACK, which leaves a red root after case 1 recoloring reaches the top. - Coloring new nodes black, which changes the black height of one path and breaks property 5 everywhere above it.
- Assuming one recoloring finishes the job: case 1 can repeat all the way up to the root.
Interview tips
- Lead with the properties and the factor-of-two argument; that alone justifies the O(log n) bound.
- Summarize insertion as "red uncle: recolor; black uncle: rotate" and draw the triangle-to-line picture.
- Mention the 2-3-4 tree correspondence; it shows you understand why the rules work, not just what they are.
- When a problem needs an ordered map, say "I will use
TreeMap/std::map, which is a red-black tree" and quote O(log n) per operation.
Real-world applications
- Ordered maps and sets in standard libraries: Java
TreeMap/TreeSet, C++std::map/std::set. - Collision handling in Java 8+
HashMap, where oversized buckets become red-black trees. - Linux process scheduling (CFS and EEVDF), epoll, and high-resolution timers.
- Interval trees and order-statistic trees built by augmenting red-black nodes.
- Persistent and functional maps in languages that need cheap, balanced updates.
Practice problems
Test yourself
Which of these is not one of the red-black tree properties?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.