What is a Red-Black Tree?
A Red-Black Tree is a self-balancing Binary Search Tree that keeps itself roughly balanced by coloring every node either red or black and enforcing a small set of rules about how those colors can be arranged. Unlike an AVL tree, which balances strictly by height, a Red-Black Tree balances by color — and that looser constraint is exactly what makes it cheaper to maintain.
The Five Red-Black Properties
The five rules (the "red-black properties") together guarantee that the longest possible root-to-leaf path is never more than twice as long as the shortest one. That's a weaker balance guarantee than AVL's, but it's enough to keep every operation at O(log n), and it means Red-Black Trees need at most one or two rotations per insertion or deletion — compared to AVL, which can cascade rotations back up the tree. This is why Red-Black Trees are the default choice inside C++'s `std::map`/`std::set`, Java's `TreeMap`/`TreeSet`, and the Linux kernel's process scheduler and virtual memory management.
How Does Insertion Fix a Violation?
Insertion always starts the same way a plain BST insertion does, and the new node is always colored red. Coloring it red (rather than black) means it can never violate the "same black-height on every path" rule by itself — the only rule a fresh red leaf can break is "a red node can't have a red parent." If that happens, a fixup procedure runs, walking back up the tree recoloring nodes and, when recoloring alone isn't enough, performing at most two rotations to restore all five properties.
Algorithm Steps (Insertion)
- Insert the new node the normal BST way, and color it red
- While the new node's parent is red (property 4 is violated), look at the uncle (the grandparent's other child):
- Uncle is red → recolor the parent and uncle to black, the grandparent to red, then continue fixing up from the grandparent
- Uncle is black (or missing) and the node forms a 'zig-zag' with its parent → rotate at the parent first to straighten it into a line
- Uncle is black (or missing) and the node forms a straight line with its parent → recolor parent black and grandparent red, then rotate at the grandparent
- Color the root black (in case it was colored red during the loop)
Time Complexity
- Best/Average/Worst Case: Height is always O(log n) → O(log n).
Time Complexity Analysis
Insertion (with fixup) needs O(1) extra space beyond the recursion/loop state — only a constant number of pointers get rewired or recolored, no matter how large the tree is.