RB Trees
RB Trees
Red-black trees
Carola Wenk
• Find 10 22
8 15
12 17
10 22
8 15
12 17
3 18
8 15
• Balanced search trees (guarantee
height of O(log n) for n elements) 12 17
10 25
2-3-4-trees) 2 7 8 11 14 20 23 24 27 40 50
17
keys as split-values in 1 6 12 17 26 41 43 59
internal nodes 6 8 12 14 26 35 41 42 59 61
3 18
null null
10 22 h=4
null
8 11 26
null null null null null null
3 18
null null
10 22 h=4
null
8 11 26
null null null null null null
3 18
null null
10 22 h=4
null
8 11 26
null null null null null null
3 18 bh = 2
null null
bh = 1 10 22 h=4
null
bh = 1 8 11 26
null null null null null null
bh = 0
5. All simple paths from any node x, excluding
x, to a descendant leaf have the same
number of black nodes = black-height(x).
9/13/17 CMPS 2200 Intro. to Algorithms 10
Height of a red-black tree
Theorem. A red-black tree with n keys has height
h 2 log(n + 1).
Proof.
INTUITION: T
• Merge red nodes
into their black
parents.
Rotation Example A
LEFT-ROTATE(A)
B
31 RIGHT-ROTATE(20) 31
9 41 9 41
6 20 39 42 6 16 39 42
2 8 16 22 2 8 15 20
In-order(v){
15 17 11 17 22
if v==null return;
In-order(v.left);
11 print(v.key+” ”);
In-order(v.right);
}
In-order traversal: In-order traversal:
2 6 8 9 11 15 16 17 20 22 31 39 41 42 2 6 8 9 11 15 16 17 20 22 31 39 41 42
8 11 26
15
15
15
C LEFT-ROTATE(A) C
y y
A B
x B x A
p[x] = left[p[p[x]]
y right[p[p[x]]
Transform to Case 3.
color[y] = BLACK
x = right[p[x]]
9/13/17 CMPS 2200 Intro. to Algorithms 35
Case 3
C
RIGHT-ROTATE(C)
y (and recolor) B
B
A C
x A
Done! No more
p[x] = left[p[p[x]] violations of RB
y right[p[p[x]] property 4 are
color[y] = BLACK possible.
x = left[p[x]]
9/13/17 CMPS 2200 Intro. to Algorithms 36
Analysis
C RIGHT-ROTATE(A) C
y A y B
x
x B
A
p[x] = right[p[p[x]]
y left[p[p[x]]
Transform to Case 3’.
color[y] = BLACK
x = left[p[x]]
9/13/17 CMPS 2200 Intro. to Algorithms 40
Case 3’
LEFT-ROTATE(C)
C
x (and recolor) B
y B
C A
Done! No more
p[x] = right[p[p[x]] violations of RB
y left[p[p[x]] property 4 are
color[y] = BLACK possible.
x = right[p[x]]
9/13/17 CMPS 2200 Intro. to Algorithms 41