Professional Documents
Culture Documents
Session (20)-2hrs
16.12.2020
AVL Search Tree
1 1
B C
0 1 -
0
D E F G 1
0
0 0 - 0 M
K
H I 1 J
0
N
AVL Search Tree
-
10 1
1 1
7 40
0 1 -
0 45 1
3 8 30
0
0 0 - 0 60
1 20 35
1 5
0
25
put(9)
-
10 1
0 1 1
7 40
0 1 -
0 - 45 1
3 8 1 30
0
0 0 0 - 0 60
1 20 35
1 5 9
0
25
put(29)
-
10 1
1 1
7 40
0 1 -
0 45 1
3 8 30
-2 0
0 0 - 0 60
1 20 35
1 5
0 -1
25
29 0
put(29)
-
10 1
1 1
7 40
0 1 -
0 45 1
3 8 30
0
0 0 0 0 60
35
1 5 25
0 0
20 29
RR rotation.
Example for right-right case:
insert(26)
15
15
8 24
8 22
24 4 10 22 25
4 10 19
3 6 3 6 19 23
23 25 26
26
Insert 6, 3, 1
Insert 7
6
4 9
1 5 8
7
Rotation in an AVL Tree
2 2
6 6
1 2 1 1
4 9 4 8
0 0 1 0 0 0 0
1 5 8 1 5 7 9
0
7
AVL Insertion: Generalised Case-I
Consider a valid
AVL subtree
j
k h
h
h
Z
X Y
AVL Insertion: Generalized Case-I
j Inserting into X
destroys the AVL
property at node j
k h
h+1 h Z
Y
X
AVL Insertion: Generalized Case-I
j Do a “right rotation”
k h
h+1 h Z
Y
X
Right rotation
j Do a “right rotation”
k h
h+1 h Z
Y
X
CASE LL Rotation
“Right rotation” done!
k (“Left rotation” is mirror
symmetric)
h+1
j
h h
X Y Z
AVL property has been restored!
More Examples
2
0 Insert 5, 40
1 3
0 0
2 3
5 5
2 2
0 0
1 3 1 3
0 0 0 0
2 3 2 3
5 5
5 5 5 5
4
Now Insert 45 0
Insert 45
2 2
0 0
1 3 1 3
0 0 0 0
2 3 2 4
5 5
5 5 5 0
3 4
4
Imbalance 5 5
0
4
5
2
0
New Case 1 4
0 0
5 3
0 4
2 3 5
2 5 5
0 3
1 3 4
0 0 2
2 4 0
5
5 0 1 3
3 4 0 0
5 5 Imbalance 2 4
5
5 0
3 4
5 5
Insertion of 34 3
4
2
Double rotation 1
0
3
0 0
2
5
5
3
2 5
0 3
1 3 4 4
0 0 0
Imbalance 2 4
5 4
5 0
2 5
3 4
5 5 0
1 3
Insertion of 34 3 0 5
4 3 4
5
0 0
2 3 4
5
AVL Insertion: New Case
Consider a valid
AVL subtree
j
k h
h h Z
X Y
AVL Insertion: New Case
Inserting into Y
destroys the j Does “right rotation”
restore balance?
AVL property
at node j
k h
h h+1 Z
X
Y
AVL Insertion: New Case
k “Right rotation”
does not restore
balance… now k is
h j out of balance
X h+1
h
Z
Y
AVL Insertion: Zig Zag Case
Consider the structure
of subtree Y… j
k h
h h+1 Z
X
Y
AVL Insertion: Inside Case
Y = node i and
subtrees V and W
j
k h
h
i h+1 Z
X h or h-1
V W
AVL Insertion: Inside Case
j We will do a left-right
“double rotation” . . .
k
i Z
X
V W
Double rotation : first rotation
j left rotation complete
i
k Z
W
X V
Double rotation : second
rotation
j Now do a right rotation
i
k Z
W
X V
Double rotation : second
rotation
right rotation complete
k j
h h
h or h-1
X V W Z
• Build an AVL tree with the following
values:
15, 20, 24, 10, 13, 7, 30, 36, 25
15, 20, 24, 10, 13, 7, 30, 36, 25
20
15
15 24
20
10
24
13
20 20
13 24 15 24
10 15 13
10
15, 20, 24, 10, 13, 7, 30, 36, 25
20
13
13 24 10 20
10 15 7 15 24
7 30
13 36
10 20
7 15 30
24 36
15, 20, 24, 10, 13, 7, 30, 36, 25
13 13
10 20 10 20
7 15 30 7 15 24
24 36 30
25 13 25 36
10 24
7 20 30
15 25 36
AVL Rotations
• RR
• LL
• RL
• LR