How a red-black tree fixes insert with colors

Short answer: A red-black tree is a binary search tree with red and black nodes. The root is black, every red node has two black children, and every path from a node to a leaf sentinel carries the same number of black nodes. Those rules keep the height at most 2 log₂(n+1). Insert colors the new node red and repairs with recoloring and at most two rotations. Delete is the longer case. Search, insert, and delete are O(log n) worst case.


What the problem actually asks

AVL stores a height and rotates to keep factors tiny. A red-black tree stores one bit and keeps a weaker invariant that is still strong enough for a logarithmic height. The black-height rule says no path is more than twice another, because a red node must be followed by a black one, so at most half the nodes on a path are red.

Insert puts a red node at a leaf so the black-height does not change. The only violation is a red child of a red parent. The uncle’s color decides the repair. A red uncle recolors and moves the problem toward the root. A black uncle rotates.


What the algorithm guarantees

All dictionary operations are O(log n) worst case. Extra memory is one color bit and the child pointers, usually with a black sentinel instead of null so the leaf rule is uniform. The in-order sequence is the sorted order. Standard-library ordered maps are often red-black trees, because the insert fixup is a short loop and the constant factors compete well with AVL.

Delete removes a node and can leave a double-black hole. The fixup pushes that hole toward the root by rotations and recolors that depend on the sibling. It is the part to implement from a case table, not from memory of the insert loop. A tree that only implements insert and search still needs the insert uncle cases, or a sorted insert paints a red path and the height bound is gone.


The working steps

  1. Search for the key. On a miss, create a red node in that leaf position. A duplicate is an update of the existing node, not a second insert.
  2. While the parent is red, inspect the uncle. If the uncle is red, color the parent and the uncle black, color the grandparent red, and continue from the grandparent.
  3. If the uncle is black and the node is an inner child, rotate the parent so the node becomes an outer child. Then color the parent black, the grandparent red, and rotate the grandparent.
  4. Color the root black at the end. The black-height rule is restored.
  5. For delete, if the removed color was black, run the double-black fixup from the hole, using the sibling’s color and the sibling’s children, until the hole is a red node that can be painted black or the root is reached.

The 2 log(n+1) height is looser than AVL’s and still logarithmic. A red-black tree is not a B-tree, and painting nodes red and black without the uncle test does not keep the black-height. Hash tables are the alternative when order and predecessor queries are not required.


Approaches that look simpler and fail

Approach Why it fails when a red node is given a red child and left there
Insert red and skip the uncle test A sorted sequence becomes a red chain. Paths no longer share a black-height, and the tree is a linked list.
Rotate without recoloring The shape may look balanced while two reds remain adjacent or a black-height changes on only one side.
Treat delete as the insert cases run backward Delete introduces a missing black, not a extra red. The sibling cases are a different table.
Use a null leaf as red The leaf rule counts black nodes down to a sentinel. A missing sentinel convention changes every case. Pick black sentinels and keep them.

Stricter height balance is the AVL tree. A randomized balance with the same expected depth is a treap. An ordered map that must stay logarithmic on adversarial keys is this tree or AVL, not a hash table.


A working example

This Python fragment fixes a red-black insertion by the uncle test. A red node has black children, and every path carries the same number of black nodes. Inserting 1, 2, 3 leaves a black root. It prints the inorder keys and colors, 1R 2B 3R.

RED, BLACK = "R", "B"

class N:
    def __init__(self, key, color=RED):
        self.key, self.color = key, color
        self.left = self.right = self.parent = None

def rot_left(root, x):
    y = x.right
    x.right = y.left
    if y.left:
        y.left.parent = x
    y.parent = x.parent
    if x.parent is None:
        root = y
    elif x is x.parent.left:
        x.parent.left = y
    else:
        x.parent.right = y
    y.left = x
    x.parent = y
    return root

def rot_right(root, y):
    x = y.left
    y.left = x.right
    if x.right:
        x.right.parent = y
    x.parent = y.parent
    if y.parent is None:
        root = x
    elif y is y.parent.right:
        y.parent.right = x
    else:
        y.parent.left = x
    x.right = y
    y.parent = x
    return root

def insert(root, key):
    node = N(key)
    parent = None
    cur = root
    while cur:
        parent = cur
        cur = cur.left if key < cur.key else cur.right
    node.parent = parent
    if parent is None:
        root = node
    elif key < parent.key:
        parent.left = node
    else:
        parent.right = node
    while node.parent and node.parent.color == RED:
        gp = node.parent.parent
        if node.parent is gp.left:
            uncle = gp.right
            if uncle and uncle.color == RED:
                node.parent.color = uncle.color = BLACK
                gp.color = RED
                node = gp
            else:
                if node is node.parent.right:
                    node = node.parent
                    root = rot_left(root, node)
                node.parent.color = BLACK
                gp.color = RED
                root = rot_right(root, gp)
        else:
            uncle = gp.left
            if uncle and uncle.color == RED:
                node.parent.color = uncle.color = BLACK
                gp.color = RED
                node = gp
            else:
                if node is node.parent.left:
                    node = node.parent
                    root = rot_right(root, node)
                node.parent.color = BLACK
                gp.color = RED
                root = rot_left(root, gp)
    root.color = BLACK
    return root

def walk(n, out):
    if n:
        walk(n.left, out)
        out.append(f"{n.key}{n.color}")
        walk(n.right, out)

root = None
for key in (1, 2, 3):
    root = insert(root, key)
out = []
walk(root, out)
assert out == ["1R", "2B", "3R"]
print(*out)

Where it is used

The Linux CFS scheduler orders runnable tasks in a red-black tree keyed by virtual runtime. C++ std::map and Java TreeMap are red-black trees as well. The color fixes keep the height logarithmic after an insert. An AVL tree rotates more often for a stricter height.


When you can drop this algorithm

Drop a from-scratch red-black tree when the language library already ships an ordered map. The delete fixup is easy to get wrong. Keep the structure when you are implementing that library, or when the color invariant itself is the object being discussed.


Why this stays published

We publish this so a search for a red-black tree returns the black-height rule and the uncle test that repairs a red insert. A red-black tree keeps search, insert, and delete at O(log n) by enforcing equal black-heights and repairing a red-red insertion with recoloring or at most two rotations.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *