Title: RedBlack Tree Insertion
1Red-Black Tree Insertion
Start with binary search insertion, coloring the
new node red.
12
14
9
NILl
NILl
13
15
NILl
NILl
NILl
NILl
2Recoloring Rebalancing
Right after insertion
12
14
9
NILl
NILl
13
15
NILl
NILl
NILl
18
NILl
NILl
Not affected.
How to fix?
3Recoloring Case 1
Look at the color of uncle y red.
12
14
9
y
NILl
NILl
13
15
x
18
NILl
NILl
NILl
NILl
NILl
Color parent and uncle black and grandparent red.
Done! (if violation exists, propagate coloring
upwards)
4Case 1
Uncle y is red.
c
no flip of color to red if c is root
new x
y
d
a
O(1)
x
E
D
b
A
B
C
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!
black nodes on a path from node c (inclusive)
to a leaf is unchanged.
5Recoloring Case 2
Uncle y is black.
y
5
x
7
NILl
NILl
6(No Transcript)
7Case 2
Uncle y of x is black.
And x is a left (right) child while its parent is
a right (left) child.
c
y
d
a
x
D
E
A
b
B
C
Terminate here! No propagation.
Case 3
8Recoloring Case 3
Uncle y is black.
12
12
recoloring
14
15
9
9
NILl
NILl
15
5
5
14
18
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
9Case 3
Uncle y is black.
Both x and its parent are left children or both
are right children.
c
y
b
d
x
a
C
E
D
A
B
Terminate here!
10Termination from Case 1
Terminates when either x root or parent is
black.
No action!
11Running Time of RB-Insert
The height of a red-black tree on n nodes is 2lg
(n1).
RB-Insert runs in O(lg n) time.
12Another Example of Insertion
20
10
70
80
5
50
15
NILl
NILl
NILl
NILl
75
85
60
40
NILl
NILl
NILl
NILl
30
65
55
45
35
25
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
13Insert 37
Case 1 uncle y is red.
20
10
70
80
5
50
15
NILl
NILl
NILl
85
75
NILl
40
60
NILl
NILl
NILl
NILl
30
65
55
45
NILl
NILl
NILl
NILl
NILl
NILl
25
35
NILl
NILl
NILl
14Case 1 again since uncle y is red.
20
10
70
80
5
50
15
NILl
NILl
NILl
NILl
75
85
60
40
NILl
NILl
NILl
NILl
30
65
55
45
35
25
NILl
NILl
NILl
NILl
NILl
NILl
37
NILl
NILl
NILl
NILl
NILl
15Case 2 uncle y is black x is a
left child its parent a right child.
20
70
10
80
5
50
15
NILl
NILl
NILl
85
NILl
75
40
60
NILl
NILl
NILl
NILl
30
55
65
45
35
25
NILl
NILl
NILl
NILl
NILl
NILl
37
NILl
NILl
NILl
First, right rotation.
NILl
NILl
16Case 3 uncle y is black and x is
a right child and so is its parent.
20
10
50
40
5
15
70
30
60
45
NILl
NILl
NILl
NILl
80
25
85
NILl
NILl
35
55
65
75
NILl
NILl
37
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
1750
70
20
10
40
60
80
5
85
45
30
15
55
65
75
25
35
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
37
NILl
NILl
NILl
NILl
NILl
1850
70
20
40
10
80
60
85
5
45
30
15
65
55
75
25
35
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
NILl
37
NILl
NILl
NILl
NILl
NILl