You are on page 1of 4

CS216

Fall 2001

AVL Trees Example

Insert 3

Insert 2

Insert 1 (non-AVL)

AVL

Single
rotation

Insert 5 (non-AVL)

Insert 4

Single
rotation

AVL

Insert 6 (non-AVL)

AVL
4

2
Single
rotation

Insert 7 (non-AVL)

2
1

4
5

2
6

5
3

9/27/01

Page 1 of 4

CS216

Fall 2001

AVL

Insert 16

4
Single
rotation

2
1

Insert 15 (non-AVL)

6
3

6
3

16

16
15

Step 1: Rotate child and grandchild

Step 2: Rotate node and new child (AVL)

4
Double
rotation

2
1

6
3

15
7

15

16

16

Insert 14 (non-AVL)

Step 1: Rotate child and


grandchild

Double
rotation

6
3

Step 2: Rotate node and


new child (AVL)

15
7

6
3

7
15

16
14

9/27/01

14

7
3

15

14

16
Page 2 of 4

16

CS216

Fall 2001

AVL Tree

No longer AVL, must rebalance

Insert a node

h +1

h +2

Two ways to expand subtree of height h+2:

h +1

h +1
h +2

Apply a Single Rotation

h
h +2

Apply a Double Rotation

Note: the symmetrical case is handled


identically (i.e. mirror image)

9/27/01

Page 3 of 4

CS216

Fall 2001

Single Rotation:
D

B
Single
rotation

h +1
C

h +1

h +2
Double Rotation:
B

Double
rotation

E
h-1

h -1
OR

h-1

h -1
OR
h
OR
h

h
OR

h
h +1

h +2
9/27/01

Page 4 of 4

You might also like