Date post: | 27-Jun-2015 |
Category: |
Technology |
Upload: | dexter-paul-gumahad |
View: | 411 times |
Download: | 3 times |
Red-Black Trees
Niño GuerreroDexter Paul Gumahad
Rene MaderaReymart Pagente
Data Structure || JRMSU Computer Science
Red-Black Trees
• A Red-Black tree is a binary search tree with these traits:– Every node is either red or black.– The root is always black.– If a node is red, its children must be black.– Every path from any node to a null must have the
same number of black nodes.
• Operations on Red-Black trees are O(log N).
Data Structure || JRMSU Computer Science
c
a f
b gd
e
Red-Black tree
Data Structure || JRMSU Computer Science
Red-Black Trees
• Red-black trees can be thought of as binary tree representations of a 2-3-4 tree.
• A 2-3-4 tree is a B-tree of degree 4.• This means each internal node has either 2, 3,
or 4 children.• The next slide illustrates this.
Data Structure || JRMSU Computer Science
c f
a b d e g
2-3-4 tree
Data Structure || JRMSU Computer Science
c
a f
b gd
e
c f
a b d e g
How the Trees Relate
Each black node represents a node in the 2-3-4 tree.Each red node is in the same node with its black parent.This explains why every path has the same number of black nodes.
Data Structure || JRMSU Computer Science
Mappings
a b
a
b a
b
or
a b c
b
ca
aa
Data Structure || JRMSU Computer Science
Inserting into a Red-Black Tree
• An inserted node is placed as in a binary search tree as a red node, unless it is the root.
• If the parent of the new node is also red, called a “double red”, the tree will have to be adjusted, since a red child must have a black parent.
Data Structure || JRMSU Computer Science
Two Casesa
c
bz
w
a
c
bz
wv
u
1.
2.
Inserting node z causes double red, and z’s parent has black sibling w. This occurs when a 4-node is malformed: must restructure.
Inserting node z causes double red, and z’s parent has red sibling w. This occurs when a 4-node overflows: must recolor.
Note: these are partial trees so not allof their subtrees are shown.
v
u
Data Structure || JRMSU Computer Science
a
c
b
Restructuring
a c
b
w
c
a
b
w
a
b
c
w
c
b
a
w
Double rotation Single rotation
Parent is black,children are red.
The malformed 4-node isnow a well-formed 4-node.
Data Structure || JRMSU Computer Science
Recoloring
b
d
c
w a
b
c
d
w a
b
d
c
w a
b
c
d
w a
Note: since b is now red, this can cause a double red with b’s parent.If so, the two cases are considered again for b and its parent.Data Structure || JRMSU Computer Science
Example
e e
h
e
h
k
1. Insert e 2. Insert h 3. Insert k, h hasnull (black) sibling
e
h
k
4. Restructure
e
h
k
5. Insert n, k hasred sibling
n
e
h
k
n
6. Recolor (root left black)Data Structure || JRMSU Computer Science
End
Data Structure || JRMSU Computer Science