Documente Academic
Documente Profesional
Documente Cultură
1 3
nil nil
Red-black trees are artificially full by adding
black nil nodes. 2
QED 4
Red-Black Trees (cont) Red-Black Trees (cont)
Insertion - Use normal Insert operation then repair.
If T has n internal nodes then n 2bh ( root ) 1
h(root )
Let z be the inserted node (has 2 black nil children)
lg(n + 1) bh(root)
2 If z is not the root, make z red.
h(T ) = h(root ) 2 lg(n + 1) If p[z] is black then done,
otherwise we have two adjacent red nodes.
So operations which are O(h) on binary trees are
Let y be zs uncle. x
O(lg n) on red-black trees...... provided these
operations preserve the properties of red and black p[z] y
trees.
z
Assume root is black.
nil nil
5 7
x x
y Right Rotate x
p[z] y p[z] y
x
Left Rotate y
z z
Case 1 Case 2
Left-Rotate
x x
p[z] y z y Case 3
Right-Rotate
z p[z]
End
Case 1 can repeat at most h/2 = O(lg n) times.
At most 2 rotations will be needed.
9 11
Example: Insertion
Case 3 - y is black and z is a left child. 5 29
z y
nil nil nil nil 6.5 nil nil nil nil nil nil
5.5
Case 1
nil
5.3 nil nil nil
5 Case 2 29
5 22
0 9 35
26
0
nil nil
-3 3 7 12 31 106 7 12 29
-3 3
nil nil 11 19 nil nil nil nil 6 8 11 19
-8 -2 6 8 26 35
nil nil
-8 -2
nil nil nil nil 6.5 nil nil nil nil nil nil 5.5 6.5 nil nil nil nil nil nil nil nil 106
5.5 31
nil nil nil nil
5.3 nil nil nil 5.3 nil nil nil nil nil nil nil
5 22
z w
0
z R 7 12 Case 2 29
x w -3 3
6 8 11 19 w
x L 26 35
L R -8 -2
nil nil nil x
5.5 6.5 nil nil nil nil nil nil nil nil 106
31
nil nil nil nil
Left-Rotate at z and exchange colors of z and w. 5.3 nil nil nil nil nil nil nil
Extra black node is absorbed by R. Done.
nil nil
21 23
Case 1
Left-Rotate Case 4
5 22
Case 2 Case 3 0
Right-Rotate
7 12 x 29 w
Case 4 -3 3
Left-Rotate Case 2 6 8 19
26 35
nil nil nil
-8 -2
5.5 6.5 nil nil nil nil nil nil 106
End 31
nil nil nil nil
Case 2 can repeat at most h = O(lg n) times. 5.3 nil nil nil nil nil nil nil
5 29
0
22
7 35
-3 3 12 26
6 8 31 106
nil nil 19 nil nil
-8 -2 nil
nil nil nil nil nil nil
5.5 6.5
nil nil nil nil nil nil
5.3 nil nil nil
nil nil
25