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:

h≤2log2n

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).

RuleIn plain wordsIf it breaks
The root is blackThe top node is always blackPaint it black after the climb
No two reds in a rowA red node never has a red childRotate right, then flip colors
Same number of black linksFrom the root to any empty spot, you cross the same number of black linksIt 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 childRotate 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.

  1. If only the right child is red → rotate left. Lay the red link down to the left.
  2. If the left child and its left child are both red → rotate right. Lift the middle node.
  3. If both children are red → flip colors. The two children turn black and the middle turns red.
1 2red 2 1red
Rotate left. The red link 1–2 leans right, so lay it down to the left. The node that moves up (2) takes the old top's color (black). In the demo this happens when 2 goes in.
3 2red 1red 2 1red 3red
Rotate right. 3–2–1 has two reds in a row, so stand it up with 2 in the middle. Now both children of 2 are red, so a color flip follows right away. You get this by inserting 3, 2, 1.
2 1red 3red 2red 1 3
Color flip. Seen as a 2-3 tree, this splits a temporary node holding three keys (1, 2, 3) and sends the middle key (2) up toward the parent. If 2 has a parent, the three rules are checked again there. In the demo this happens when 3 goes in.

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).

InsertedWhere it hangsFixes on the way upRootRed nodesHeight
1Empty tree, so it is the rootPaint the root black (root is red)1none0
2Right of 1Rotate left at 1 (right red)211
3Right of 2Flip colors at 2 (both red) → paint the root black (root is red)2none1
4Right of 3Rotate left at 3 (right red)232
5Right of 4Flip colors at 4 (both red) → rotate left at 2 (right red)422
6Right of 5Rotate left at 5 (right red)42, 52
7Right of 6Flip colors at 6 (both red) → flip colors at 4 (both red) → paint the root black (root is red)4none2

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

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.

OptionSearch: best / usual / worstInsert: usual / worstExtra memoryGoodBadUse it when
Plain binary search treeO(1) / O(log n) / O(n)O(log n) / O(n)Two links per nodeShort and easy. In-order listing, range searchSorted input turns it into a lineLearning, or when you can trust the insert order to be well mixed
Red-black treeO(1) / O(log n) / O(log n)O(log n) / O(log n)Two links per node + one color bitHeight stays under 2·log₂n even in the worst case. In-order listing, smallest key, range searchLonger code. Deleting is harder stillYou need keys in order and it must be fast whatever the insert order
Hash tableO(1) / O(1) / O(n)O(1) / O(n)Empty slots kept freeFastest for looking up one exact keyNo order, so range search and sorted listing must scan everythingYou 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

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 pageBook terms
red-black treered-black BST, red-black tree
left-leaning red-black treeleft-leaning red-black BST (LLRB)
red link, black linkred link, black link
empty spotnull link (counted as black)
rotate left, rotate rightleft rotation, right rotation
flip colorscolor flip
same number of black linksperfect black balance
tree of nodes holding one or two keys2-3 tree (2-3 search tree). One key is a 2-node, two keys a 3-node
a tree that keeps its balancebalanced search tree
walk left, node, rightin-order traversal
storage that finds values by keysymbol table
log₂ nlg n (log base 2)

Sources

← Binary search treesGraph search: BFS and DFS →