Lecture01_RedBlackTree
Lecture01_RedBlackTree
1 Introduction
A red-black tree is a balanced binary search tree whose height grows only logarithmically to the
number of nodes in the tree. Each node in the red-black tree has a colour, which is either red or
black. The colour is a boolean attribute that helps balancing the tree. We define the height of a
node x to be H(x) = the number of edges on a path from x down to the farthest leaf .
A binary search tree is a red-black tree if it satisfies the
following essential properties (invariants): F
1
FCAI-CU AdvDS Red-Black Trees Amin Allam
2 Insertion
A node is inserted and coloured red in order to maintain property 4. If its parent is red, one or
more of the following cases is followed to preserve property 3. If the root becomes red, it is just
converted into black. The first two cases should be continued. Symmetric cases are not shown.
The subtrees a, b, c, d, e have black roots.
2.1 Case-1
C C
A D A D
a B d e a B d e
b c b c
2.2 Case-2
C C
B D B D
A c d e A c d e
a b a b
2.3 Case-3
C
B
A d
A C
a B
a b c d
b c
2.4 Case-4
C
B
B d
A C
A c
a b c d
a b
2
FCAI-CU AdvDS Red-Black Trees Amin Allam
3 Deletion
If the physically deleted node was red, no changes are needed. Otherwise, the child of the physi-
cally deleted node gets an additional black in order to maintain property 4. The additional black
should be removed from that node to preserve property 1. If it was originally red, it is just con-
verted into black. Otherwise, one or more of the following cases is followed in order to remove
the additional black while maintaining other properties. The first two cases should be continued.
Symmetric cases are not shown.
3.1 Case-1
B D
A D B e
a b C e A C
c d a b c d
3.2 Case-2
B B
A D A D
a b C E a b C E
c d e f c d e f
3.3 Case-3
B C
A D B D
a b C e A c d e
c d a b
3.4 Case-4
B C
A C B D
a b c D A c d e
d e a b
3
FCAI-CU AdvDS Red-Black Trees Amin Allam
4 Example:
Starting from an initial empty tree, draw all intermediate trees and draw the tree after each of the
following operations:
Insert(M), Insert(T), Insert(F), Insert(Q), Insert(P), Delete(F), Delete(Q), Delete(T).
M M
M M
T F T
4.2 Insert(Q)
M M M
F T F T F T
Q Q Q
4.3 Insert(P)
M
M
F T
F Q
Q
P T
P
4.4 Delete(F)
M P
Q M Q
P T T
4
FCAI-CU AdvDS Red-Black Trees Amin Allam
4.5 Delete(Q)
P P
M T M T
4.6 Delete(T)
P P P
M M M