Avl Redblack 22 Aug
Avl Redblack 22 Aug
N0 = 1 N1 = 2 N2 =4 N3 = N1+N2+1=7
• Let x be the root of an AVL tree of height h
• S(h) : minimum number of nodes in an AVL
tree of height h
• S(h)=S(h-1)+S(h-2)+1
Smallest AVL tree
of height 7
Smallest AVL tree
of height 8
4 4
2 5 2 6
1 3 6 1 3 5 7
Insert 7,
violation at node 5 7 Single rotation
2 6
1 3 5 7
2 6 2 6
1 3 5 7 k1 1 3 5 15 k2
2 6 k1 2 7 k2
A
1 3 5 15 k3 1 3 6 k1 15 k3
k2 7 16 D 5 14 16
4 k1 7
X 2 7 k2
4 15
1 3 6 15 2 6 14 16
Insert 13 5 14 16
1 3 5 13
Y Z Single rotation
13
7 7
4 15 4 15
2 6 14 16 2 6 13 16
1 3 5 13 1 3 5 12 14
7
7
4 13
4 15
2 6 12 15
2 6 13 16
1 3 5 11 14 16
1 3 5 12 14
4 13 4 13
2 6 12 15 2 6 11 15
1 3 5 11 14 16 1 3 5 10 12 14 16
7
7
4 13
4 13
2 6 11 15
2 6 11 15
1 3 5 9 12 14 16
1 3 5 10 12 14 16
8 10
8 Insert 8, fine
9 then insert 9 double rotation
AVL Trees - Implementation
struct node
{
int data;
struct node * llink;
struct node * rlink;
int height;
};
4 15
2 6 12 21
7
Path rule Path rule Red rule
Example of a red-black tree
Search 11
60
30 80
20 50 70 90
ADD 40?
60
30 80
20 50 70 90
40
VIOLATES RED RULE,
NEED TO FLIP SOME COLORS (50)
60
30 80
20 50 70 90
40
1. Perform standard BST insertion and make the colour of
newly inserted nodes as RED.
2. If x is the root, change the colour of x as BLACK (Black
height of complete tree increases by 1).
3. Do the following if the color of x’s parent is not BLACK and x
is not the root.
a) If x’s uncle is RED
(i) Change the colour of parent and uncle as BLACK.
(ii) Colour of a grandparent as RED.
(iii) Change x = x’s grandparent, repeat steps 2 and 3 for
new x.
b) If x’s uncle is BLACK, then there can be four configurations
for x, x’s parent (p) and x’s grandparent (g) (similar to AVL)
(i) Left Left Case (p is left child of g and x is left child of p)
(ii) Left Right Case (p is left child of g and x is the right
child of p)
(iii) Right Right Case (Mirror of case i)
(iv) Right Left Case (Mirror of case ii)
4. Re-coloring after rotations:
• For Left Left Case [3.b (i)] and Right Right case [3.b (iii)],
swap colors of grandparent and parent after rotations
• For Left Right Case [3.b (ii)]and Right Left Case [3.b (iv)],
swap colors of grandparent and inserted node after
rotations
•Left Left Case (LL rotation):
•Left Right Case (LR rotation):
•Right Right Case (RR rotation):
•Right Left Case (RL rotation):
Analysis
• Go up the tree performing Case 1, which only
recolors nodes.
• If Case 2 or Case 3 occurs, perform 1 or 2
rotations, and terminate.
Running time: O(lg n) with O(1) rotations.
Applications:
1.Most of the self-balancing BST library functions like
map, multiset, and multimap in C++ ( or java
packages like java.util.TreeMap and java.util.TreeSet )
use Red-Black Trees.
Example:
Insertion into a red-black tree Example:
• Insert x =15.
• Recolor, moving the
violation up the tree.
Insertion into a red-black tree
Create a red-black tree for the following data:
3,2,5,6,10,4,7,8