DrawCode Algorithm Visualizer • Tree • Hard

Red-Black Tree Insert

Tags: Tree, Balanced BST, Red-Black, Rotation

1. One-Liner

RB insert places a new red node like BST, then recolors and rotates to fix red-red conflicts and black-height rules.


2. The Problem It Solves

Balanced search trees need fast search/insert/delete with worst-case guarantees. Red-black trees keep height ≤ 2× the black height, giving O(log n) with simpler rebalancing than AVL in many libraries (TreeMap, std::map).


3. The Core Idea

New nodes start red (avoid breaking black count). If parent is red, fix using uncle color: if uncle red → push blackness up (recolor parent, uncle, grandparent). If uncle blackrotate + recolor to eliminate double red and preserve black paths.


4. How It Works (Step-by-Step)

StepAction
1BST-insert new node z as red leaf.
2If root → paint black; done.
3While parent of z is red: let p = parent, g = grandparent, u = uncle.
4If u red: recolor p,u black, g red; z = g; continue.
5Else: align with rotations (LR/RL as needed), then rotate + recolor so black-height and no adjacent reds.

5. Dry Run Example

Insert into near-balanced tree: first recolor case bubbles red to grandparent; if uncle black, one or two rotations finish—local picture matches CLRS cases.


6. Key Properties

InvariantMeaning
Black heightSame # black nodes on root→leaf paths
No double redRed node’s parent is black
Root blackOften enforced after fixup

7. Where It Is Used

LibraryRole
Java TreeMapSorted map
C++ std::mapTypically RB
Linux kernelrbtree for intervals

8. Interview Tips

Know why new node red. Explain uncle red vs black branches. Left-leaning red-black is a simplified variant (Sedgewick). Compare amortized rotations vs AVL.


9. Comparison with Other Algorithms

TreeBalanceInsert typical
RBHeight ≤ 2bhFewer rotations
AVLStricterMore rotations
B-treeNode fanoutDisk-oriented

10. Complexity

----
InsertO(log n) time, O(1) rotations amortized typical
SpaceO(n) pointers

Implementation Example (PYTHON)

RED, BLACK = 0, 1

class RBNode:
    def __init__(self, k):
        self.k, self.c = k, RED
        self.l = self.r = self.p = None

def left_rotate(T, x):
    y = x.r
    x.r = y.l
    if y.l: y.l.p = x
    y.p = x.p
    if not x.p: T.root = y
    elif x == x.p.l: x.p.l = y
    else: x.p.r = y
    y.l, x.p = x, y

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer