A red–black tree is a self-balancing binary search tree in which every node carries one extra bit of information, its color, either red or black. A small set of coloring rules keeps the longest root-to-leaf path at most twice as long as the shortest, so search, insertion and deletion all run in O(log n) worst-case time. Among data structures used for ordered collections, it is one of the most widely deployed in practice.
The structure was introduced by Rudolf Bayer in 1972 as the symmetric binary B-tree and received its familiar name and coloring convention from Leonidas Guibas and Robert Sedgewick in 1978. Today it powers ordered maps and sets in standard libraries, the Linux kernel scheduler and memory management, and many database and networking components. The spelling red-black tree with a plain hyphen is equally common.
The five red–black tree invariants
A red–black tree is defined by five invariants that every valid tree satisfies after each operation. Leaves are modeled as black NIL sentinels, which simplifies the rules and the code that enforces them.
| Property | Rule | Why it matters |
|---|---|---|
| Coloring | Every node is red or black | Provides the one bit of balance information |
| Black root | The root is black | Simplifies the fix-up cases |
| Black leaves | Every NIL leaf is black | Gives a uniform path endpoint |
| Red rule | A red node has no red child | Prevents long chains of red nodes |
| Black-height rule | Equal black count on every root-to-leaf path | Keeps paths within a factor of two |
The red rule and the black-height rule work together. A path can at most alternate red and black nodes, so its length is bounded by twice the black height. From this it follows that a tree with n internal nodes has a height of at most 2 log2(n + 1), which is the formal basis of the logarithmic guarantee.
How insertion and deletion restore balance
Every update starts as an ordinary binary search tree operation and is followed by a fix-up phase that repairs any violated invariant. The repair uses only two tools: recoloring nodes and rotations, which are local pointer changes that preserve the in-order sequence of keys.
Insertion adds the new node in red, because a red node never changes black height. If its parent is also red, the algorithm inspects the uncle node. A red uncle triggers recoloring and moves the problem two levels up, while a black uncle is resolved with one or two rotations. Consequently, insertion needs at most two rotations, plus O(log n) recolorings.
Deletion is more intricate. Removing a black node reduces the black height of one path, which the algorithm models as an extra black on a replacement node, often called a double-black. It then works through four symmetric cases based on the sibling and its children, and it finishes with at most three rotations. The small, bounded number of structural changes is a key reason red–black trees suit concurrent and persistent implementations.
| Operation | Worst-case time | Rotations needed |
|---|---|---|
| Search | O(log n) | None |
| Insertion | O(log n) | At most 2 |
| Deletion | O(log n) | At most 3 |
| In-order traversal | O(n) | None |
| Minimum or maximum | O(log n), O(1) with cached pointer | None |
Red–black trees compared with related structures
Choosing a red–black tree is usually a choice between balance strictness and update cost. The closest rival is the AVL tree, which keeps tighter balance, while skip lists, B-trees and hash tables solve related problems with different trade-offs.
| Structure | Worst-case height or lookup | Update cost | Best fit |
|---|---|---|---|
| Red–black tree | About 2 log2 n | Few rotations | Mixed reads and writes in memory |
| AVL tree | About 1.44 log2 n | More rotations | Read-heavy workloads |
| B-tree | log base m of n | Node splits and merges | Disk and SSD storage |
| Skip list | O(log n) expected only | Probabilistic | Simple concurrent ordered sets |
| Hash table | O(1) average, no ordering | Occasional resize | Unordered key lookup |
A red–black tree is also isomorphic to a 2-3-4 tree, a B-tree of order four: each black node together with its red children corresponds to one multi-key node. This view explains the fix-up cases intuitively, and it underlies the simplified left-leaning red–black tree variant that Sedgewick proposed in 2008.
Where red–black trees are used in practice
Red–black trees are the default implementation of ordered containers in several major libraries, because they combine guaranteed bounds with modest update cost. They appear wherever software needs to keep keys sorted while they change frequently.
- C++ std::map and std::set in the common GCC, Clang and Microsoft implementations.
- Java TreeMap and TreeSet, and the tree bins that replace long chains inside Java HashMap.
- The Linux Completely Fair Scheduler, which orders runnable tasks by virtual runtime.
- Linux virtual memory areas, timers and the ext3 directory index in various kernel subsystems.
Limitations and common implementation mistakes
Red–black trees are notoriously error-prone to implement from scratch. Each node needs a parent pointer or an explicit path stack, and the symmetric left and right cases double the amount of code. Their pointer-heavy layout also yields poor cache locality compared with arrays or B-trees, so on modern hardware a sorted array or a B-tree often outperforms them for read-mostly data.
- Forgetting to recolor the root black after insertion fix-up, which silently breaks the second property.
- Mishandling the NIL sentinel in deletion, especially when the replaced node has no children.
- Skipping invariant checks in tests; a validator that recomputes black height catches most defects early.
- Assuming AVL-level balance, which leads to underestimated worst-case search depth.
A plain-language summary
A red–black tree is a way of storing items in sorted order so they can be found quickly, even while items are constantly added and removed. Imagine a family tree of numbers where each person is painted red or black. A few simple painting rules stop any branch from growing too long.
Whenever an item is added or removed, the tree repaints a few nodes and twists a small part of itself to keep its shape. As a result, finding any item among a million takes only about forty steps at most, never a slow walk through the whole list.
An example from practice
A trading platform keeps an in-memory order book for each stock, where buy and sell orders must stay sorted by price while thousands of orders arrive and are canceled every second. The engineers store each side of the book in a red–black tree keyed by price level, with each node holding a queue of orders at that price.
With about 50,000 active price levels, a lookup or update touches roughly at most 32 nodes, and each insertion or cancellation performs no more than three rotations. The best bid and ask are read in constant time from cached minimum and maximum pointers, and latency stays predictable during volume spikes, which a hash table could not offer because it does not keep prices in order.