CS 332: Algorithms: Red-Black Trees
CS 332: Algorithms: Red-Black Trees
Red-Black Trees
H
D
TreeWalk(x)
TreeWalk(left[x]);
print(x);
TreeWalk(right[x]);
Easy to show by induction on the BST property
Preorder tree walk: print root, then left, then right
Postorder tree walk: print left, then right, then root
k != key[x])
Running time:
Best case: (n lg n) (its a comparison sort)
Worst case: O(n2)
Average case: O(n lg n) (its a quicksort!)
for i=1 to n
TreeInsert(A[i]);
InorderTreeWalk(root);
3 1 8 2 6 7 5
1 2
8 6 7 5
2
6 7 5
5
6
5
Successor:
x has a right subtree: successor is minimum node in right
subtree
x has no right subtree: successor is first ancestor of x whose
left child is also ancestor of x
Intuition: As long as you move to the left up the tree, youre
F
B
H
D
K
Example: delete K
or H or B
Red-Black Trees
Red-black trees:
Binary search trees augmented with node color
Operations designed to guarantee that the height
h = O(lg n)
First: describe the properties of red-black trees
Then: prove that these guarantee h = O(lg n)
Finally: describe operations on red-black trees
Red-Black Properties
The red-black properties:
Red-Black Trees
Put example on board and verify properties:
1.
2.
3.
4.
with height h?
A: a height-h node has black-height h/2
Theorem: A red-black tree with n internal
nodes has height h 2 lg(n + 1)
How do you suppose well prove this?
= 20 - 1
= 0 internal nodes (TRUE)
n 2bh(root) - 1
n 2h/2 - 1
lg(n+1) h/2
h 2 lg(n + 1)
Thus h = O(lg n)
(Why?)
(Why?)
(Why?)
(Why?)
O(lg n) height
Corollary: These operations take O(lg n) time:
Minimum(), Maximum()
Successor(), Predecessor()
Search()