Essential Data Structures home

Red-Black Tree

A binary search tree that paints each node red or black and uses the colors to keep itself balanced, so search, insert, and delete stay logarithmic no matter the insertion order.

30 20 40 10 25 35 50 A red node always has black children, and every root-to-leaf path passes through the same number of black nodes.
Illustration: a red-black tree holding 10, 20, 25, 30, 35, 40, and 50. The colors enforce the balance, so the height stays small no matter the insertion order.

What it is

A red-black tree is a binary search tree with one extra bit of information per node: a color, red or black. The colors must follow four rules. The root is black. Every empty leaf is black. A red node always has black children, so two red nodes never sit in a row. And every path from a node down to a leaf passes through the same number of black nodes, a count called the black-height.

Those four rules are enough to guarantee balance. If the black-height is b, the tree holds at least 2^b - 1 nodes, so the height can never exceed about twice the logarithm of n. More precisely, a red-black tree with n nodes has height at most 2 log2(n + 1). The tree is allowed to lean a little, unlike an AVL tree, but it can never degenerate into a line the way a plain binary search tree can.

The idea was published by Rudolf Bayer in 1972 as the symmetric binary B-tree, and the red-black name comes from Guibas and Sedgewick in 1978. It is the most widely used self-balancing tree in practice, because it rebalances less strictly than an AVL tree and so pays less on insert and delete, while still keeping every operation logarithmic.

How it works

Search works exactly like a plain binary search tree: walk down comparing values until you find the value or reach an empty leaf. The height guarantee is what makes that walk short.

Insert also starts like a plain binary search tree insert: walk down to an empty spot and put the new node there, colored red. Red is chosen because it cannot break the black-height rule, so only one rule can be broken: the new red node might have a red parent. The fix-up then walks up, repairing that violation. If the new node's uncle is red, the fix is recoloring: parent and uncle turn black, grandparent turns red, and the problem moves up one level. If the uncle is black, the fix is rotations: a triangle shape needs two rotations, a straight line needs one, and the colors are swapped as the rotation happens. An insertion needs at most two rotations, and then the tree is valid again.

Delete is the harder operation. Removing a black node lowers the black-height on one path, so the tree gains a temporary double-black node, and the fix-up pushes that extra blackness up or sideways with recoloring and rotations until it disappears. A deletion needs at most three rotations. In practice, libraries hide this machinery, but the guarantee is the same: every operation finishes in O(log n) time.

Complexity

OperationAverageWorst case
SearchO(log n)O(log n)
InsertO(log n)O(log n)
DeleteO(log n)O(log n)
Minimum / maximumO(log n)O(log n)
In-order traversalO(n)O(n)

n is the number of items. The worst case column is O(log n) for search, insert, and delete because the color rules keep the height at most 2 log2(n + 1), so the tree can never degenerate into a line the way a plain binary search tree can.

When to use it, and when not to

Use a red-black tree when you need ordered data with guaranteed fast lookup, insert, and delete, and the data arrives in an order you do not control. It is the default choice for an ordered map or set in most standard libraries, and it is the right shape when inserts and deletes are frequent, because it rebalances less often than an AVL tree.

Do not use a red-black tree when the data is unordered and you only need fast lookup by key, because a hash table is faster there, with O(1) average lookup and no ordering cost. Do not use it when lookups dominate and inserts are rare, because an AVL tree stays more tightly balanced and searches slightly faster. Python's built-in dict and set are hash tables, not trees, and Python has no built-in red-black tree.

Where you meet it

Red-black trees run the ordered containers of most languages. Java's TreeMap and TreeSet, C++'s std::map and std::set, and C#'s SortedDictionary are all red-black trees underneath. The Linux kernel uses its own red-black tree for the completely fair scheduler, which keeps runnable processes ordered by how much CPU time they have had, and for tracking memory mappings. Database engines and file systems lean on the same balancing idea, usually in B-tree form, whenever sorted data must stay searchable after arbitrary inserts.

In Python

class Node:
    def __init__(self, value, color="red"):
        self.value = value
        self.color = color
        self.left = None
        self.right = None
        self.parent = None

class RedBlackTree:
    def __init__(self):
        self.nil = Node(None, "black")
        self.nil.left = self.nil.right = self.nil.parent = self.nil
        self.root = self.nil

    def rotate_left(self, x):
        y = x.right
        x.right = y.left
        if y.left is not self.nil:
            y.left.parent = x
        y.parent = x.parent
        if x.parent is self.nil:
            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 is not self.nil:
            x.right.parent = y
        x.parent = y.parent
        if y.parent is self.nil:
            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, value):
        z = Node(value)
        z.left = z.right = self.nil
        y = self.nil
        x = self.root
        while x is not self.nil:
            y = x
            if z.value < x.value:
                x = x.left
            elif z.value > x.value:
                x = x.right
            else:
                return  # duplicate, ignore it
        z.parent = y
        if y is self.nil:
            self.root = z
        elif z.value < y.value:
            y.left = z
        else:
            y.right = z
        z.color = "red"
        self._fix_insert(z)

    def _fix_insert(self, z):
        while z.parent.color == "red":
            if z.parent is z.parent.parent.left:
                y = z.parent.parent.right  # uncle
                if y.color == "red":       # case 1: recolor
                    z.parent.color = "black"
                    y.color = "black"
                    z.parent.parent.color = "red"
                    z = z.parent.parent
                else:
                    if z is z.parent.right:  # case 2: triangle
                        z = z.parent
                        self.rotate_left(z)
                    z.parent.color = "black"  # case 3: line
                    z.parent.parent.color = "red"
                    self.rotate_right(z.parent.parent)
            else:  # mirror image of the above
                y = z.parent.parent.left
                if y.color == "red":
                    z.parent.color = "black"
                    y.color = "black"
                    z.parent.parent.color = "red"
                    z = z.parent.parent
                else:
                    if z is z.parent.left:
                        z = z.parent
                        self.rotate_right(z)
                    z.parent.color = "black"
                    z.parent.parent.color = "red"
                    self.rotate_left(z.parent.parent)
        self.root.color = "black"

    def inorder(self, node, out):
        if node is not self.nil:
            self.inorder(node.left, out)
            out.append(node.value)
            self.inorder(node.right, out)

    def search(self, value):
        x = self.root
        while x is not self.nil and x.value != value:
            x = x.left if value < x.value else x.right
        return x is not self.nil

    def height(self, node):
        if node is self.nil:
            return 0
        return 1 + max(self.height(node.left), self.height(node.right))

tree = RedBlackTree()
for v in [30, 20, 40, 10, 25, 35, 50]:
    tree.insert(v)

out = []
tree.inorder(tree.root, out)
print(out)                # [10, 20, 25, 30, 35, 40, 50]
print(tree.root.value)    # 30
print(tree.root.color)    # black
print(tree.height(tree.root))  # 3

# Insert in sorted order: a plain BST would become a line.
tree2 = RedBlackTree()
for v in [10, 20, 30, 40, 50, 60, 70, 80]:
    tree2.insert(v)
print(tree2.height(tree2.root))  # 4, still balanced
print(tree2.search(60))          # True
print(tree2.search(99))          # False

In short: a red-black tree is a binary search tree with a color on every node and four rules the colors must obey. Those rules cap the height at about twice the logarithm of n, so search, insert, and delete are O(log n) in the worst case, with at most a couple of rotations per update.

Sources

← Home