PPT

Red-Black Tree
Neil Tang
02/07/2008
CS223 Advanced Data Structures and Algorithms
1
Class Overview
 Definition
 Tree height
 Rotation and color flip
 Insert
 Delete
CS223 Advanced Data Structures and Algorithms
2
Definition
A red-black tree is a special binary search tree in which
 every node is either red or black;
 the root is black;
 every leaf (null) is black;
 if a node is red, then both its children are black;
 every simple path from a node to a descendant leaf
contains the same number of black nodes.
CS223 Advanced Data Structures and Algorithms
3
Height
 Theorem: A red-black tree with N nodes has height at most
2log(N+1). (pp.274 Cormen’s book)
 Experiments suggests that the average red-black tree is
about as deep as an average AVL tree.
 The rotation happens less frequently.
CS223 Advanced Data Structures and Algorithms
4
An Example
CS223 Advanced Data Structures and Algorithms
5
Rotation if S is Black
CS223 Advanced Data Structures and Algorithms
6
Color Flip if S is red
CS223 Advanced Data Structures and Algorithms
7
Example: Insert 45
CS223 Advanced Data Structures and Algorithms
8
Insert
CS223 Advanced Data Structures and Algorithms
9
Insert
CS223 Advanced Data Structures and Algorithms
10
Insert
CS223 Advanced Data Structures and Algorithms
11
Delete
15
5
3
Case 1:
15
16
12
10
5
20
18
13
23
3
18
10
15
5
3
7
16
12
10
20
13
18
3
23
20
18
12
10
23
13
6
7
7
15
5
16
12
10
15
5
6
3
23
6
7
Case 3:
20
12
6
Case 2:
16
6
20
13
18
23
3
10
CS223 Advanced Data Structures and Algorithms
16
12
6
7
15
5
20
13
18
23
7
12
Delete
 In terms of deletion, everything boils down to delete a leaf.
 Deletion of a red leaf is trivial.
 How to delete a black leaf: Change the color of the leaf to
be deleted to red by a top-down pass.
CS223 Advanced Data Structures and Algorithms
13
Three Cases When X Has Two Black Children
CS223 Advanced Data Structures and Algorithms
14