Red-black tree: a tree that rebalances on every insert
Insert 1, 2, 3, ... into a plain binary search tree and every value goes to the right, so the tree becomes one long line. A red-black tree fixes a few spots on every insert and stays short. Insert numbers one at a time and see what gets fixed, and why, step by step.
What this page covers. This page covers only inserting into a "left-leaning red-black tree", a version with fewer cases than the original textbook red-black tree because red links lean left only and the fixes shrink to three (rotate left, rotate right, color flip); deleting is not covered.
Short answer. A red-black tree is a binary search tree where every node is red or black. A new value walks down like in a plain tree and is added as a red node. Then, on the way back up to the root, every broken rule is fixed with rotate left, rotate right or color flip. So even values that arrive in sorted order do not make a line, the height never goes above 2·log₂n, and search and insert stay proportional to log n even in the worst case.
Press "Next" to take one step. The first input is 1 to 7. You can type up to 15 whole numbers from 0 to 99, separated by commas or spaces. Red nodes have a thick red border and the word "red"; black nodes are solid black circles. The dashed orange ring marks the node being compared or fixed in this step, and orange arrows and words show what this step does (the comparison and the branch taken, the broken rule, "moved up" and "moved down", "red → black"). A faint dashed ring is an empty spot or the spot a rotation left. Each node's left-right position follows its value, so a rotation never moves a node sideways, only up or down.
Definitions
The sections below explain with pictures and experiments. The textbook definitions are these. This page covers the left-leaning red-black tree from the source (algs4). The color of a node is the color of the link coming down to it from its parent, and links to empty spots count as black. n is the number of nodes, and the height h is the number of links from the root to the farthest node. The binary search tree page counts levels instead, which gives one more.
- red-black tree
- A binary search tree where each node is red or black and these rules hold. (1) The root is black. (2) A red node has no red child. (3) From the root to any empty spot, you cross the same number of black links. (4) A red node is always the left child of its parent (a rule of the version on this page). With these rules, the height is never more than:
- black height
- The number of black links you cross going down from a node x to an empty spot below it. Rule (3) says this number is the same on every path from the root. Red links never come two in a row, so any path has at most twice as many links as the black height.
- rotation
- An operation that swaps which of a parent and its child is on top. A left rotation lifts the right child into the parent's place and moves the parent down to be its left child. A right rotation does the opposite. It changes only three links and keeps the in-order order, so the binary search tree rule and the number of black links stay the same.
- color flip
- An operation on a node whose two children are both red: it makes the two children black and the node red. It does not change the number of black links.
- 2-3 search tree
- A search tree where each node is a 2-node with one key and two children, or a 3-node with two keys and three children. If the keys of a 3-node are a < b, keys in the left subtree are smaller than a, keys in the middle are between a and b, and keys in the right are bigger than b. In a balanced 2-3 tree, every empty spot is the same distance from the root. If you treat two nodes joined by a red link in a red-black tree as one 3-node, you get a 2-3 tree.
1. Why you need it
A binary search tree only keeps "smaller on the left, larger on the right" and hangs each value in an empty spot. So the insert order decides the shape. If values come smallest first, like 1, 2, 3, ..., each one lands at the far right and the tree becomes a line. Keys that only grow, like ID numbers or timestamps, arrive this way. Searching a line is the same as scanning from start to end: with n values you compare n times.
A red-black tree fixes only a few spots on the path from the new node back up to the root on every insert, and that keeps it short. The 1 to 7 in the demo would be a line of height 6 in a plain tree, but in a red-black tree it becomes a full tree of height 2.
2. The rules it keeps
A node's color is the color of the link coming down to it from its parent. A red node is "a node joined to its parent by a red link". Links to empty spots (missing children) count as black. Height is the number of links from the root to the farthest node (one node alone has height 0).
| Rule | In plain words | If it breaks |
|---|---|---|
| The root is black | The top node is always black | Paint it black after the climb |
| No two reds in a row | A red node never has a red child | Rotate right, then flip colors |
| Same number of black links | From the root to any empty spot, you cross the same number of black links | It never breaks: new nodes are red, and rotations and color flips do not change this count |
| Red leans left only (this version's rule) | A red node is always its parent's left child | Rotate left |
Why these rules keep it balanced. Treat two nodes joined by a red link as one lump (a node with two keys). Then the tree is a tree of nodes holding one or two keys: a 2-3 tree. If you draw the red links flat, every empty spot sits at the same distance from the root (the "1-1 correspondence" in the source). Counting only black links gives a full tree, and since reds never come in a row, a path can hold at most as many red links as black ones.
3. The three fixes
On the way up from the new node to the root, check these three in this order at every node you pass. At the top, paint the root black. A rotation changes only three links. The order "left < top < right" stays, so it is still a binary search tree.
- If only the right child is red → rotate left. Lay the red link down to the left.
- If the left child and its left child are both red → rotate right. Lift the middle node.
- If both children are red → flip colors. The two children turn black and the middle turns red.
4. Follow it by hand: 1 to 7 in order
This is the demo's first input. Up to "where it hangs" the walk down is exactly like a plain tree. "Fixes on the way up" lists the three rules and the root painting in the order they happen; the words in brackets say what was broken at that moment (the same words as the orange labels in the demo).
| Inserted | Where it hangs | Fixes on the way up | Root | Red nodes | Height |
|---|---|---|---|---|---|
| 1 | Empty tree, so it is the root | Paint the root black (root is red) | 1 | none | 0 |
| 2 | Right of 1 | Rotate left at 1 (right red) | 2 | 1 | 1 |
| 3 | Right of 2 | Flip colors at 2 (both red) → paint the root black (root is red) | 2 | none | 1 |
| 4 | Right of 3 | Rotate left at 3 (right red) | 2 | 3 | 2 |
| 5 | Right of 4 | Flip colors at 4 (both red) → rotate left at 2 (right red) | 4 | 2 | 2 |
| 6 | Right of 5 | Rotate left at 5 (right red) | 4 | 2, 5 | 2 |
| 7 | Right of 6 | Flip colors at 6 (both red) → flip colors at 4 (both red) → paint the root black (root is red) | 4 | none | 2 |
The final tree is full: 4 at the root, 2 and 6 below it, and 1, 3, 5, 7 at the bottom. Walk it left, node, right and you get 1, 2, 3, 4, 5, 6, 7 in sorted order.
Try this. ① The first input, 1 to 7, takes 44 steps in all. You see rotate left 4 times, color flip 4 times and root painting 3 times, and never rotate right, because values that come smallest first always land on the right. Each rotation and color flip is shown in two steps: "mark what is broken" and "after the fix". ② Change the input to 7 6 5 4 3 2 1. Now it takes 49 steps, with rotate right 4 times and no rotate left. The final tree is the same as in ①. ③ Insert in any order you like. At every "Done inserting" step, every red node is someone's left child, and no two red nodes touch.
5. The height never goes above 2·log₂n
height ≤ 2 · log₂ n
height: the number of links from the root to the farthest node.n: the number of nodes (values) in the tree.log₂ n: how many times you multiply 2 to reach n. For n = 8 it is 3, for n = 1,000,000 it is about 20. The source writes it aslg.2 ·: twice that.
The source states: "The height of a red-black BST with N nodes is no more than 2 lg N." So search and insert take logarithmic time even in the worst case. With a million values the height stays at 40 or below, while the same values inserted in sorted order into a plain tree give height 999,999. Search goes down one level at a time from the root, so the height sets the largest number of comparisons.
Both trees use the same scale. Change how many values go in (7 to 15) with the slider or the number box. In the right picture, the hollow red rings are red nodes.
Try this. ① With 7 values the plain tree has height 6 and the red-black tree has height 2. ② At 8 values the red-black tree reaches height 3 and stays at 3 all the way to 15. The plain tree grows by 1 with every value and reaches 14 at 15 values. ③ 2·log₂n is 5.61 at 7 values and 7.81 at 15, so the red-black tree stays well below that line.
6. When to use what
Big O in plain words: O(1) means about the same no matter how big n is, O(log n) means one more step when n doubles, O(n) means twice the work when n doubles.
| Option | Search: best / usual / worst | Insert: usual / worst | Extra memory | Good | Bad | Use it when |
|---|---|---|---|---|---|---|
| Plain binary search tree | O(1) / O(log n) / O(n) | O(log n) / O(n) | Two links per node | Short and easy. In-order listing, range search | Sorted input turns it into a line | Learning, or when you can trust the insert order to be well mixed |
| Red-black tree | O(1) / O(log n) / O(log n) | O(log n) / O(log n) | Two links per node + one color bit | Height stays under 2·log₂n even in the worst case. In-order listing, smallest key, range search | Longer code. Deleting is harder still | You need keys in order and it must be fast whatever the insert order |
| Hash table | O(1) / O(1) / O(n) | O(1) / O(n) | Empty slots kept free | Fastest for looking up one exact key | No order, so range search and sorted listing must scan everything | You only look up and insert by exact key |
"Best" for search is when the key sits at the root. The hash table's worst case is when many keys pile into one slot.
7. In Python
class Node:
def __init__(self, key): self.key, self.left, self.right, self.red = key, None, None, True
def is_red(n): return n is not None and n.red
def rotate_left(h): x = h.right; h.right, x.left = x.left, h; x.red, h.red = h.red, True; return x
def rotate_right(h): x = h.left; h.left, x.right = x.right, h; x.red, h.red = h.red, True; return x
def put(h, key):
if h is None: return Node(key) # a new node is red
if key < h.key: h.left = put(h.left, key)
elif key > h.key: h.right = put(h.right, key)
if is_red(h.right) and not is_red(h.left): h = rotate_left(h) # red leans left only
if is_red(h.left) and is_red(h.left.left): h = rotate_right(h) # two reds in a row
if is_red(h.left) and is_red(h.right): h.red, h.left.red, h.right.red = True, False, False # color flip
return h
root = None
for key in range(1, 8): root = put(root, key); root.red = False # the root is always black
At the end root.key is 4 and every node is black (the same final tree as in the demo). The three fix lines run in the same order as the source's RedBlackBST.java. Python's standard library has no balanced tree like this. If you only look up exact keys, use a dict (a hash table).
Where it is used
- Storage that needs keys in order (a symbol table). Find the smallest or largest key, the key just below or above a given key, a key's rank, or how many keys fall in a range. The source says these, along with search and insert, take logarithmic time in the worst case in a red-black tree.
- When keys may arrive already sorted. Even ever-growing IDs do not make a line (demo ②).
- When you do not want a separate search routine. Search uses the plain binary search tree code as is. Colors only matter during inserts.
Common questions
Why is a new node added red?
If you added it black, that one path would cross one more black link, and the rule "every path to an empty spot crosses the same number of black links" would break. Adding it red keeps that rule. The only rules that can break are "red leans left only" and "no two reds in a row", and rotations and color flips fix those right there.
How is this different from the textbook red-black tree?
In the original textbook red-black tree a red node may also sit on the right, so an insert has more cases to check. The left-leaning version on this page keeps red links on the left only, so the fixes on insert shrink to three: rotate left, rotate right and color flip. Both search exactly like a plain binary search tree.
Does search look at the colors?
No. The colors are only used to keep the tree balanced during inserts. Search uses the plain binary search tree code without any change.
Words
| Words on this page | Book terms |
|---|---|
| red-black tree | red-black BST, red-black tree |
| left-leaning red-black tree | left-leaning red-black BST (LLRB) |
| red link, black link | red link, black link |
| empty spot | null link (counted as black) |
| rotate left, rotate right | left rotation, right rotation |
| flip colors | color flip |
| same number of black links | perfect black balance |
| tree of nodes holding one or two keys | 2-3 tree (2-3 search tree). One key is a 2-node, two keys a 3-node |
| a tree that keeps its balance | balanced search tree |
| walk left, node, right | in-order traversal |
| storage that finds values by key | symbol table |
| log₂ n | lg n (log base 2) |
Sources
- Robert Sedgewick, Kevin Wayne, Algorithms, 4th edition, 3.3 Balanced Search Trees. 2-3 trees and the 1-1 correspondence, red links that lean left, left and right rotation, color flip, keeping the root black, the proposition that the height is at most 2 lg N, the operations that take logarithmic time in the worst case, reusing the plain search code, and the rule checks (is23, isBalanced).