Lecture 15 notes

Download Report

Transcript Lecture 15 notes

Red-Black trees
Red-black trees are 2-3-4 trees represented as binary trees at the expense of
one extra bit per node. The idea is to represent 3- and 4-nodes as minibinary trees, bound by “red” links.
Red-black trees have the following properties:
1
2
3
4
3-nodes can be represented in two different ways.
Two red links never follow one another in a row.
All paths in the red-black tree have the same number of black links.
One path containing red and black links can be twice as long as
another path containing only black links.
5 All path lengths are proportional to log N.
6 Nodes with data items equal to a given node can fall on both sides of
that node.
Examples
2
1 2 3
1
3
15
9 15
9
OR
9
15
16
10 16 20
10
3 7 8
12 13
18
25
7
3
20
12
8
18
13
25
Operations on red-black trees
Search: same as in binary search trees, except for the need of a boolean
attribute black that each node must maintain.
Insert: same as in 2-3-4 trees, except that the colors of the links must be
taken into consideration.
Delete: similar to deletion in binary search trees. We can always delete a
node that has at least one external child. However, if the key to be deleted
is stored in a node with no external children, we move there the key of its
inorder predecessor (or successor), and delete that node instead.
Example:
7
5
4
2
8
5
4
9
2
8
9
Insert operation: example
Insert 15
16
10
7
3
20
12
8
18
25
16
13
10
7
3
20
13
8
Split
12
18
15
25
Splitting 4-nodes without rotation
Case1: Splitting a 4-node connected to a 2-node
Splitting 4-nodes without rotation (contd.)
Case2A: Splitting a 4-node connected to a 3-node
Splitting 4-nodes with single rotation
Case2B: Splitting a 4-node connected to a 3-node
Splitting 4-nodes with double rotation
Case2C: Splitting a 4-node connected to a 3-node
Reduced
to case 2B
The insertRB method
Algorithm insertRB (T, newData, precedes)
boolean success := false
if (T = null) {
NodeRBtree node = new NodeRBtree(newData)
success := true }
else {
if (nodeType(T)= 4)
splitroot(T)
NodeRBtree p := T; NodeRBtree parent := null; boolean done := false
while (! done) {
if (nodeType(p) = 4) {
if (nodeType (parent) = 2) then splitChildOf2 (p, parent)
else splitChildOf3 (p, parent) }
int compareResult := compare (p, newData, precedes)
if (compareResult < 0) then success := false; done := true
else
if (compareResult = 0) then insertData (p, newData, precedes); success:=true; done:=true
else
advance (p, parent, compareResult)
} // end while
} // end else