Red-Black Trees: Introduction To Algorithms
Red-Black Trees: Introduction To Algorithms
Red-Black Trees
CSE 680
Prof. Roger Crawfis
Red-black trees: Overview
30 47
38 50
nil[T]
Height of a Red-black Tree
Height of a node:
h(x) = number of edges in a longest path to a
leaf.
Black-height of a node x, bh(x):
bh(x) = number of black nodes (including nil[T ])
on the path from x to leaf, not counting x.
Black-height of a red-black tree is the
black-height of its root.
By Property 5, black height is well defined.
Height of a Red-black Tree
h=4
Example: 26 bh=2
Height of a node:
h(x) = # of edges in a h=3
17 h=1 41 bh=2
longest path to a bh=1
leaf.
Black-height of a node h=2
h=2 30
bh(x) = # of black bh=1
47 bh=1
nodes on path from x h=1
bh=1
to leaf, not counting x. h=1 50
38
bh=1
How are they related?
bh(x) ≤ h(x) ≤ 2 bh(x)
nil[T]
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
Bound on RB Tree Height
x Left-Rotate(T, x) y
y Right-Rotate(T, y) x
Rotations
Rotations are the basic tree-restructuring operation for almost all
balanced search trees.
Rotation takes a red-black-tree and a node,
Changes pointers to change the local structure, and
Won’t violate the binary-search-tree property.
Left rotation and right rotation are inverses.
x Left-Rotate(T, x) y
y Right-Rotate(T, y) x
Left Rotation – Pseudo-code
Left-Rotate (T, x)
1. y right[x] // Set y.
2. right[x] left[y] //Turn y’s left subtree into x’s right subtree.
3. if left[y] nil[T ]
4. then p[left[y]] x
5. p[y] p[x] // Link x’s parent to y.
6. if p[x] = nil[T ]
7. then root[T ] y x Left-Rotate(T, x) y
8. else if x = left[p[x]]
9. then left[p[x]] y y Right-Rotate(T, y) x
10. else right[p[x]] y
11. left[y] x // Put x on y’s left.
12. p[x] y
Rotation
z
z
B A
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.
Case 3 – y is black, z is a left
child
C B
p[z]
B y A C
z
A