Upload
aliyaraza1
View
8
Download
1
Embed Size (px)
Citation preview
CS216 Fall 2001
9/27/01 Page 1 of 4
AVL Trees Example
Insert 3 Insert 2 Insert 1 (non-AVL) AVL
Insert 4 Insert 5 (non-AVL) AVL
Insert 6 (non-AVL) AVL Insert 7 (non-AVL)
3 3
2
3
2
1
2
1 3Singlerotation
2
1 3
4
5
1 3
4
Singlerotation
2
1 4
53
2
1 4
53
6
2
Singlerotation
4
2 5
1 3 6
4
2 5
1 3 6
7
CS216 Fall 2001
9/27/01 Page 2 of 4
AVL Insert 16 Insert 15 (non-AVL)
Step 1: Rotate child and grandchild Step 2: Rotate node and new child (AVL)
Insert 14 (non-AVL) Step 1: Rotate child and Step 2: Rotate node andgrandchild new child (AVL)
4
2 6
1 3 75
Singlerotation
16
4
2 6
1 3 75
4
2
1 3 75
16
15
Doublerotation
16
6
4
2
1 3 75
15
6
4
2
1 3 155
167
Doublerotation
4
2
1 3 75
15
14 16
5
4
2
1 3 156
1614
6
6
4
2
1 3 155
167
14
67
CS216 Fall 2001
9/27/01 Page 3 of 4
AVL Tree No longer AVL, must rebalance
Two ways to expand subtree of height h+2:
h h +2
Insert a node
h h +1
h
h h +1
h
h +1 h
Note: the symmetrical case is handledidentically (i.e. mirror image)
Apply a Single Rotation Apply a Double Rotation
h +2 h +2
CS216 Fall 2001
9/27/01 Page 4 of 4
Single Rotation:
Double Rotation:
h
h h +1
A
B
D
C E
Singlerotation
E
D
h +1
h h
B
A C
G
F
h
h h -1
D
C E
h
ORh-1 h
ORh h
B
A
D
h h
B
A C
Doublerotation
h -1 h
F
E G
ORh-1 h
OR h h
h +2
h +2
h +1