Red Black Tree: by P.Vasuki
Red Black Tree: by P.Vasuki
by
P.VASUKI
Red-Black Trees
• Auto Balanced binary search tree
• Tree is balanced after every insert
and delete
• Entire tree is not checked for
balancing on insert.
Definition
• A red-black tree is a binary search
tree where:
– Every node is either red or black.
– Each NULL pointer is considered to be a black
node
– If a node is red, then both of its children are
black.
– Every path from a node to a leaf contains the
same number of black nodes.
The black-height of a node
• In a red-black tree black height is
the number of black nodes on any
path to a leaf, not counting n.
• Red black tree is balanced with
respect to black count
Example
Insert 8 8 8
Root Can’t be red
Insert 18 8
88
Bottom Up Insertion
1:Paent and Uncle are of same color change color
of uncle, parent and grant parent and check new
situation
: Both parent and uncle are red -- color parent and uncle
black, color grandparent red, point X to grandparent,
check new situation
18 18
16 88 16 88
91 GP to be colored as red 91
As is root retain black
Bottom Up Insertion 2 -ZIG-
ZIG ROTATION
18 Parent and uncle are of different color
Insert 94
and now the insertion is on right – right
16 88 rotate new node with grand parent rotate
once.
91
P and GP are same direction
Null node – 94
considered Rotate P with GP –
as black Change the color of P & gp
18
(zig-zig): Parent is red, but uncle is
16 black. X and its parent are both left or
91 both right children -- color parent black,
color grandparent red, rotate right on
grandparent
88 94
Bottom Up Insertion 2 -ZIG-
ZIG
• (zig-zag): Uncle and Parent
are not of same color and
20 Insert 17 parent, grand parent are in
different direction do double
16
91
rotation.
• Parent is red, but uncle is
18 88 94 black. X and its parent are
opposite type children
17
• color grandparent red, color
Node x
X black, rotate left on parent,
rotate right on grandparent
Zig zag rotation
2.Step 2 Rotate on Parent
20
Insert 17 20
Insert 17
16 GP
91 16 GP
91
P X
18 88 94 17 88 94
17 Node x 18
P
1.Step 1 change color of X 2.Step 2 Rotate on Parent
and GP
20
Insert 17
20
Insert 17
GP 17 X 91
16
91
P GP
18 88 94 16 18 88 94
P
17
Node x
• Deletion