Red-Black Tree Insertion Start with binary search insertion, coloring the new node red NIL l Insert 18 NIL l NIL l 1315 NIL l
Recoloring & Rebalancing NIL l NIL l Properties 1, 2, 3, 5? Property 4? violation! Not affected. How to fix? Right after insertion:
Recoloring – Case NIL l 18 NIL l x y Look at the color of uncle y – red. Color parent and uncle black and grandparent red. Done! (if violation exists, propagate coloring upwards) NIL l NIL l
Case 1 Uncle y is red. a A B ED C Recoloring y new x Propagate upwards (if c’s parent is red). x O(1) #black nodes on a path from node c (inclusive) to a leaf is unchanged. Any path entering subtree A, B, C, D, or E will pass through the same number of black nodes to reach a leaf. Property 5 maintained! no flip of color to red if c is root d c b c A BC DE b ad
Recoloring – Case 2 NIL l 5 x y Uncle y is black. NIL l Newly inserted Rot 1 Rot 2 Rotation NIL l NIL l 1418 NIL l NIL l
Rotation 2 Recoloring NIL l NIL l 18 NIL l NIL l NIL l 18 NIL l 15 12
Case 2 Uncle y of x is black. d c b BC A DE x y recolor b and c Terminate here! No propagation. And x is a left (right) child while its parent is a right (left) child. Case 3 a y x d a b AB CDE c x a DE BCA d b c
Recoloring – Case 3 15 NIL l NIL l 5 x y Uncle y is black. Newly inserted NIL l recoloring 18 NIL l NIL l 9 12
Case 3 Uncle y is black. a b AB CED y x recolor b and c Terminate here! Both x and its parent are left children or both are right children. d c c D a E BC d A x b
Termination from Case 1 Case 1 changes into case 2 or 3, terminating after ≤ 2 rotations. Or case 1 all the way (repeatedly upward propagations). Terminates when either x = root or parent is black. b a x root No action!
Running Time of RB-Insert The height of a red-black tree on n nodes is 2lg (n+1). RB-Insert runs in O(lg n) time. Binary search tree insertion takes O(lg n). Case 1 may repeat O(lg n) times (the pointer x moves up the tree). Case 2 or 3 terminates RB-Insert after at most two tree rotations.
NIL l 55 NIL l Another Example of Insertion NIL l
NIL l 55 NIL l Insert 37 Binary tree insertion. Color it red. Properties 1, 2, 3, 5 satisfied but property 4 violated. x y Case 1: uncle y is red. Propagate violation upward by recoloring NIL l 37 35
NIL l 55 NIL l 37 NIL l x y Case 1 again since uncle y is red. Propagate violation upward by recoloring. NIL l
NIL l 55 NIL l 37 NIL l Case 2: uncle y is black; x is a left child; its parent a right child. x y z First, right rotation. 85 NIL l NIL l 45 75
NIL l 55 NIL l 37 NIL l y x z Case 3: uncle y is black and x is a right child and so is its parent. Next, rotate around z NIL l 50 NIL l NIL l 80
NIL l 37 NIL l y x z Recolor NIL l 25 NIL l NIL l 40 20
NIL l 37 NIL l y x z Done NIL l NIL l NIL l