AlgoPlusAlgoPlus
Learn/Data Structures & Algorithms
Lesson

Red-Black Tree

A BST kept roughly balanced by painting nodes red or black and obeying a few color rules — cheap recolors first, rotations only when forced.

9 min read Watch it move Build it

A red-black tree is a binary search tree that stays balanced using one cheap trick: every node is painted red or black, and a handful of color rules force the tree to stay roughly even. It accepts a slightly looser balance than an AVL tree in exchange for doing fewer rotations on insert and delete — which is why it backs many standard-library maps and OS schedulers.

The color rules

  1. 1Every node is red or black; the root is black.
  2. 2No red node may have a red child (the red-red rule).
  3. 3Every path from a node down to an empty leaf crosses the same number of black nodes — its black-height.
Why these rules force balance
Equal black-height on every path means no path can have more black nodes than another. And since reds can't stack, the longest possible path (alternating red-black) is at most twice the shortest (all black). A factor-of-two height bound is all you need to guarantee O(log n).

Fixing an insert — recolor before you rotate

A new node always arrives red (adding a red node never changes any path's black-height, so it's the least disruptive choice). If its parent is black, you're done. If the parent is also red, the red-red rule breaks and you fix up — and the uncle (the parent's sibling) decides how:

  1. 1Uncle is red -> just recolor: flip the parent and uncle to black and the grandparent to red, then repeat the check upward from the grandparent. No rotation needed.
  2. 2Uncle is black -> rotate: a single or double rotation around the grandparent, plus a recolor, repairs the structure locally and terminates.
red-red violation, RED uncle -> recolor only:

      G(black)                 G(red)
     /      \                 /     \
  P(red)   U(red)   -->   P(black) U(black)
   /                       /
  N(red)  <- new          N(red)   (now legal; re-check at G)
AVL vs red-black, again
AVL keeps height tighter, winning on lookups. Red-black tolerates more imbalance but guarantees at most a constant number of rotations per update — winning on insert/delete-heavy workloads. Both are O(log n); the constant factors differ.
Recolors can cascade, rotations can't
The red-uncle case can ripple recoloring all the way up to the root — that's still O(log n) work but many cheap steps. A single insert never needs more than two rotations to settle, no matter the tree size.
OperationTimeSpace
Search / insert / delete · height <= 2 log(n+1)O(log n)O(log n)
Rotations per update · at most 2 (insert) / 3 (delete)O(1)O(1)
Recolors per insert · may cascade upwardO(log n)O(1)
Check yourself
When a newly inserted red node's parent is also red, what decides whether the fix-up recolors or rotates?