Lec6 - RedBlackTrees
Lec6 - RedBlackTrees
• Binary search tree + 1 bit per node: the attribute color, which is
either red or black.
• All other attributes of BSTs are inherited:
•key, left, right, and p.
5. For each node, all paths from the node to descendant leaves
contain the same number of black nodes.
Red-black Tree – Example
26
Remember: every internal
node has two children, even
though nil leaves are not
17 41 usually shown.
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
• Example: h=4
26 bh=2
• Height of a node:
h(x) = # of edges in a h=1
h=3
17 41 bh=2
longest path to a leaf. bh=1
• Black-height of a node bh(x) = #
of black nodes on path from x to
leaf, not counting x. h=2
h=2 30 47 bh=1
bh=1 h=1
• How are they related? bh=1
• bh(x) ≤ h(x) ≤ 2 bh(x) 38 h=1 50
bh=1
nil[T]
Lemma “RB Height”
x Left-Rotate(T, x) y
y Right-Rotate(T, y) x
Rotations
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
5. For each node, all paths from the node to descendant leaves
contain the same number of black nodes.
Insertion in RB Trees
• Problem: we may have one pair of consecutive reds where we did the
insertion.
• Solution: rotate it up the tree and away…
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
CC BB
p[z]
B y A C
z
A