Professional Documents
Culture Documents
= red node
The coloring ensures that no path on the way from the root to a leaf is more than twice as long as any other path
!
Red-Black Trees
Red-Black Trees
NULL pointers are considered black nodes Black-height = the number of black nodes on any path from, but not including, a node to a leaf
4.
Every node is colored either red or black The root is black If a node is red, its children must be black Every path from a node to a NULL pointer must contain the same number of black nodes
Red-Black Trees 3
= red node
Red-Black Trees
Balance
Due to the coloring (balancing), the height of the tree is at most 2lg(N+1) Search is the same as for a BST - O(lg n) When inserting and removing, the tree must be adjusted so the properties of the red-black tree still hold
Re-Balancing
When inserting and removing we rebalance the tree by doing rotations and recoloring
Red-Black Trees
Red-Black Trees
Right Rotate
Right rotate around y Y X a b a > X c <
Red-Black Trees
Left Rotate
Left rotate around X X X Y a b c a b BST ordering properties hold: X < Y c a b Y X Y c
X < b Y
<
Y
7
a > X c <
Red-Black Trees
X < b Y
<
Y
8
Left Rotate
In class exercise - left rotate around 11
7 4 3 2 6 9 14 12 17 20 11 18 19 22
Left Rotate
7 11 9 14 12 18 19 22 17 20
7 18 11 9 12 14 17 20 19
22
Red-Black Trees
Red-Black Trees
10
2.
If the parent of the newly inserted node is black, color the node red and we are done If the parent of the newly inserted node is red - violation of property 3, two possible cases
1. Sibling of parent (uncle) is black - rotate depending on whether or not x is a right child 2. Sibling of parent (uncle) is red - recolor
Red-Black Trees
11
Red-Black Trees
12
Insert 17
10 3 1 6 8 9 15
10
= black node
10 3 1 6 8 9 15 17
Red-Black Trees
13
Red-Black Trees
14
Insert 5
Violation of property 3
Insert 5
10 15 3 17 9 y 5
Red-Black Trees
10 10 15 3 17 1 y 6 5
Red-Black Trees
10 3 1 6 5 8
15 8 x 9
y x
8 17 1 5 3 6 9
15
1 6
x 9
17
Violation of property 3
15
16
Insert 5
10 8 x 3 6 5 5
Red-Black Trees 17
Insert 2
8 15 y x 3 6 9 8 10 15 y 1 2 5 3 6 9 10 15 17 17
17 1
Red-Black Trees
18
Insert 4
8 8 3 1 2 x 4
Red-Black Trees
Insert 41
3 1 2 17 x y
19 Red-Black Trees 20
10 9 5 15 17 6
10 9 15
In class exercise - insert the following values one at a time into an initially empty red-black tree
!
6 5
41
41
Insert 38
Insert 31
41 38 x 31 38
41 y x
38 31 41 y
Red-Black Trees
21
Red-Black Trees
22
Insert 12
x 38 31 12 x 41 y 12 31 x 38 41 y
Insert 19
38 31 38 41 y 12 19 y x 12 41 19 31 y 38 41
31 12
Red-Black Trees
23
Red-Black Trees
24
Insert 19
38 31 19 x 12 y 41 x 12 19 31 x y 38 41
Insert 8
38 19 12 8 31 y 8 41 12 x 19 31 y 38 41
Red-Black Trees
25
Red-Black Trees
26