Professional Documents
Culture Documents
Left-Rotate(T,x)
y = right[x]
right[x] = left[y]
p[left[y]] = x
p[y] = p[x]
if p[x] == nil[T] then root[T] = y
else
if x == left[p[x]] then left[p[x]] = y
else
right[p[x]] = y
left[y] = x
p[x] = y
Red Black Insert
RB-Insert(T,z)
y = nil[T]
x = root[T]
while x != nil[T]
y=x
if key[z] < key[x] then
x = left[x]
else
x = right[x]
p[z] = y
if y = nil[T]
root[T] = z left[z] = nil[T]
else right[z] = nil[T]
if key[z] < key[y] then color[z] = RED
left[y] = z RB-Insert-fixup(T,z)
else
right[y] = z
RB-Insert-fixup(T,z)
RB-Insert-fixup(T,z) {
while(z's parent is Red) {
set y to be z's uncle
if uncle y is Red {
color parent and uncle black
color grandparent red
set z to grandparent
}
else { // the uncle is black
if (zig zag) { // make it a zig zig
set z to parent
rotate to zig zig
}
// rotate the zig zig and finish
color parent of z black
color grandparent of z red
rotate grand parent of z
}
} // end while
color root black
}
Problem
• Insert the following numbers (one by one) into
a Red Black Tree. Draw the tree after each
insertion. Place an ‘R’ or circle red nodes.
• 1,2,3,4,10,14,7,6,12
Answer
• Here is the final tree.
4
/ \
2R 10R
/ \ / \
1 3 7 14
/ /
6R 12R