RBTrees
RBTrees
30 47
38 50
nil[T]
redblack - 6 Comp 122, Spring 2004
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 node:
h=3
17 h=1 41 bh=2
h(x) = # of edges in a bh=1
longest path to a leaf.
Black-height of a node h=2
h=2 30
bh(x) = # of black nodes 47 bh=1
bh=1 h=1
on path from x to leaf, bh=1
not counting x. 38 h=1 50
bh=1
How are they related?
» bh(x) ≤ h(x) ≤ 2 bh(x) nil[T]
redblack - 8 Comp 122, Spring 2004
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
redblack - 9 Comp 122, Spring 2004
Bound on RB Tree Height
Lemma: The subtree rooted at any node x has
2bh(x)–1 internal nodes.
Proof: By induction on height of x.
» Base Case: Height h(x) = 0 x is a leaf bh(x) = 0.
Subtree has 20–1 = 0 nodes.
x Left-Rotate(T, x) y
y Right-Rotate(T, y) x
x Left-Rotate(T, x) y
y Right-Rotate(T, y) x
redblack - 14 Comp 122, Spring 2004
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]]
then left[p[x]] y Right-Rotate(T, y)
y x
9.
10. else right[p[x]] y
11. left[y] x // Put x on y’s left.
12. p[x] 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.
z
A
Make p[z] black and p[p[z]] red.
Then right rotate on p[p[z]]. Ensures property 4 is maintained.
No longer have 2 reds in a row.
p[z] is now black no more iterations.
Make w red and w’s left child black.
Then right rotate on w.
New sibling w of x is black with a red right child case 4.