Professional Documents
Culture Documents
Red-Black Trees
CSE 680
Prof. Roger Crawfis
nodes.
Operations
case.
Operations
case.
Easiest
Red-black Tree
Binary
We
Red-black Properties
1.
2.
3.
4.
5.
17
30
47
38
nil[T]
50
of a node:
leaf.
Black-height
of a node x, bh(x):
bh(x)
Black-height
Example:
Height
of a node:
h(x) = # of edges in a
longest path to a leaf.
Black-height of a node
bh(x) = # of black
nodes on path from x to
leaf, not counting x.
How
17
h=1
bh=1
h=2 30
bh=1
h=3
41 bh=2
h=1
bh=1
38
h=2
47 bh=1
h=1 50
bh=1
Lemma RB Height
Consider a node x in an RB tree: The longest
descending path from x to a leaf has length h(x),
which is at most twice the length of the shortest
descending path from x to a leaf.
Proof:
# black nodes on any path from x = bh(x) (prop 5)
# nodes on shortest path from x, s(x). (prop 1)
But, there are no consecutive red (prop 4),
and we end with black (prop 3), so h(x) 2 bh(x).
Thus, h(x) 2 s(x). QED
Rotations
Left-Rotate(T, x)
Right-Rotate(T, y)
Rotations
Left-Rotate(T, x)
Right-Rotate(T, y)
9.9.
then
Right-Rotate(T, y) x
y
thenleft[p[x]]
left[p[x]]
yy
10.
else
10.
elseright[p[x]]
right[p[x]]
yy
11.
left[y]
x
//
Put
x
on
ys
left.
11. left[y] x // Put x on ys left.
12.
12. p[x]
p[x]
yy
Rotation
The
Left
Reminder: Red-black
Properties
1.
2.
3.
4.
5.
Insertion in RB Trees
Insertion
RB-Insert(x).
Color
RB-Insert-Fixup.
Insertion Fixup
Problem:
Insertion Fixup
RB-Insert-Fixup
RB-Insert-Fixup(T,
(T, z)
z)
1.1.
while
whilecolor[p[z]]
color[p[z]]=
=RED
RED
2.2.
do
doififp[z]
p[z]=
=left[p[p[z]]]
left[p[p[z]]]
3.3.
then
thenyy
right[p[p[z]]]
right[p[p[z]]]
4.4.
ififcolor[y]
color[y]=
=RED
RED
5.5.
then
thencolor[p[z]]
color[p[z]]
BLACK
BLACK ////Case
Case11
6.6.
color[y]
////Case
color[y]
BLACK
BLACK
Case11
7.7.
color[p[p[z]]]
color[p[p[z]]]
RED
RED ////Case
Case11
8.8.
zz
////Case
p[p[z]]
p[p[z]]
Case11
Insertion Fixup
RB-Insert-Fixup(T,
RB-Insert-Fixup(T,z)
z)(Contd.)
(Contd.)
9.
else
9.
elseififzz=
=right[p[z]]
right[p[z]] ////color[y]
color[y]RED
RED
10.
then
////Case
10.
thenzz
p[z]
p[z]
Case22
11.
LEFT-ROTATE(T,
////Case
11.
LEFT-ROTATE(T,z)
z)
Case22
12.
color[p[z]]
////Case
12.
color[p[z]]
BLACK
BLACK
Case33
13.
color[p[p[z]]]
////Case
13.
color[p[p[z]]]
RED
RED
Case33
14.
RIGHT-ROTATE(T,
14.
RIGHT-ROTATE(T,p[p[z]])
p[p[z]]) ////Case
Case33
15.
else
15.
else(if(ifp[z]
p[z]==right[p[p[z]]])(same
right[p[p[z]]])(sameas
as10-14
10-14
16.
with
16.
withright
rightand
andleft
leftexchanged)
exchanged)
17.
17. color[root[T
color[root[T]]]]
BLACK
BLACK
new z
C
p[z]
D
z
p[p[z]] (zs grandparent) must be black, since z and p[z] are both red and there are no
other violations of property 4.
Make p[z] and y black now z and p[z] are not both red. But property 5 might now be
violated.
p[z]
p[z]
y
Left rotate around p[z], p[z] and z switch roles now z is a left child, and both
z and p[z] are red.
Takes us immediately to case 3.
C
p[z]
Algorithm Analysis
O(lg
Deletion
Deletion,
OK.
Black?
Steps:
Do