Basic Text

advertisement
Insertion into a Red-Black Tree
CS 483
For definitions of red-black tree and rotations see either your
class notes or the textbook. In the pictures that follow only
the relevant nodes are shown -- you may imagine subtrees.
To insert a new value into a red-black tree we first we do an
ordinary BST insert of the new value N and color the new node
red. (Note: this insert puts N below an old "real" leaf, not a
ghost leaf.) We will assume that N's parent, here labeled
"Dad", is the left child of Dad's parent here labeled "Grandpa
Oscar". The right-side case is the mirror image of the
discussion which follows.
This insert does not affect the black count but may result in a
violation of the red-red property if Dad is red. This must be
fixed. Two cases arise, as shown here, depending on whether N
is a left or right child of Dad.
Case 1: N is left child of Dad
B
Case 2: N is right child of Dad
B
Grandpa Oscar
Grandpa Oscar
R
R
Dad
Aunt Betty
Dad
Aunt Betty
R
N
R
N
It will be enough to consider Case 1 since Case 2 can be
transformed into Case 1 with a left rotate around Dad (without
changing black counts).
From here there are two subcases. Dad's sibling, here labeled
Aunt Betty, could be either red or black. If Aunt Betty is red
we can just recolor the nodes: Dad and Aunt Betty become black
and Grandpa Oscar becomes red.
- 1 -
Case 1
After recoloring
Case 1.1: Aunt Betty is Red
R
B
Grandpa Oscar
Grandpa Oscar
B
R
Dad
R
Dad
Aunt Betty
Aunt Betty
B
R
R
N
N
The recoloring doen't change the black count since coloring
Grandpa Oscar red decrements the black count on both of its
subtrees and making Dad and Aunt Betty black increments each
side. A problem may be introduced, however, if Grandpa Oscar's
father is red. This pushex the red-red violation up the tree.
If Aunt Betty is black we must rotate and recolor. First we
rotate right around Grandpa Oscar. This decreases the black
count on the left of where Dad is now by one but leaves the
black count on the right unchanged. Next recolor Dad black
(increasing the black count on both sides by one) and recolor
Grandpa Oscar red (decreasing the black count on the right by
one). The black count is restored and red-red violation is
removed.
Case 1.2: Aunt Betty is black
After rotating and recoloring
B
B
Dad
Grandpa Oscar
R
R
Dad
B
Aunt Betty
N
R
Grandpa Oscar
R
B
N
- 2 -
Aunt Betty
In all of the cases above the black counts are restored but in
Case 1.1 a red-red violation may occur between Grandpa Oscar and
his parent. In this case apply the same operations just
described on the new level. It is possible that the red-red
violation continues all the way up to the root. In this case
recolor the root black which changes the black count on both of
its subtrees by one hence keeping the black count balance.
- 3 -
Download