We insert a new item (k,
e) at the parent v of the leaf
reached by searching for k
We preserve the depth property but
We may cause an overflow (i.e., node v may become a 5-node)
Example:
inserting key 30 causes an overflow
We handle an overflowat a 5-node v with a split operation:
let v1,
…, v5 be the
children of v and k1, …,
k4 be the
keys of v
node v
is replaced nodes v' and v"
v' is a 3-node
with keys k1,
k2 and
children v1,
v2,
v3
v" is a 2-node
with key k4
and children v4,
v5
key k3
is inserted into the parent u
of v (a new root may
be created)
The overflow may propagate to the parent node u
Algorithm insertItem(k, e) 1.We search for key k to locate the insertion node v 2.We add the new item (k, e) at node v 3. while overflow(v)
if isRoot(v) create a new empty root above v v
← split(v)
Analysis of Insertion in a (2,4) Tree 24Trees.pdf 10
Let T be a (2,4)
tree with n items
Tree T has O(log n) height
Searching takes O(log
n) time because we visit
O(log n) nodes
Restoring Node-Size
Property takes O(log
n) time because each split
takes O(1) time and we
perform O(log n) splits
Thus, an insertion in a (2,4) tree takes O(log n) time
To perform operation insertItem(k, e), we execute the
insertion algorithm for binary search trees and color red the newly
inserted node z unless it is
the root
We preserve the root, external, and depth properties
If the parent v
of z is black, we also
preserve the
internal
property and we are done
If the parent v
of z is red, we have a double red(i.e., a violation
of
the internal property),
which requires a reorganization of the tree
Example where the insertion of 4 causes a double red:
Consider a double red
with child z and parent v, and let w be the sibling of v
Case 1: w is
black
The double red
is an incorrect replacement of a
4-node
Restructuring:
we change the 4-node replacement
Case 2: w is
red
The double red
corresponds to an overflow
Recoloring:
we perform the equivalent of a split
Case 1: A restructuring remediesa
child-parent double red when the
parent red node has a black sibling
It is equivalent to restoring the correct replacement of a
4-node
The internal property is restored and the other properties
are preserved
There are four restructuring configurations depending on
whether the double red
nodes are left or right children
Case 2: A recoloring
remedies a child-parent double
redwhen the
parent red node has a red
sibling:
The parent v and
its sibling w become black and
the grandparent u becomes red, unless it is the root
It is equivalent to performing a split on a 5-node
The double redviolation
may propagate to the grandparent u
Analysis of Insertion in a Red-Black Tree
Recall that a red-black
tree has O(log n) height
Step 1 takes O(log
n) time because we
visit O(log n) nodes
Step 2 takes O(1)
time
Step 3 takes O(log
n) time because we
perform
O(log n) recolorings, each taking O(1) time, and
at most one restructuring taking O(1) time
Thus, an insertion in a red-black tree takes O(log n) time