Sei sulla pagina 1di 4

CS216

Fall 2001

AVL Trees Example

Insert 3
3

Insert 2
3

Insert 1 (non-AVL)
3

AVL
2

2 1

Single rotation

Insert 4
2

Insert 5 (non-AVL)
2
Single rotation

AVL
2

3 4

1 3

Insert 6 (non-AVL)
2 4
Single rotation

AVL
4 2 1 3 5 6 1 2

Insert 7 (non-AVL)
4 5 3 6 7

1 3

5 6

9/27/01

Page 1 of 4

CS216

Fall 2001

AVL
4
Single rotation

Insert 16
4 6 2 7 1 3 5 6 7 16 1 2 3

Insert 15 (non-AVL)
4 6 5 7

2 1 3 5

16 15

Step 1: Rotate child and grandchild


4
Double rotation

Step 2: Rotate node and new child (AVL)


4

2 1 3 5

6 7 1

2 3 5

6 15 7

15

16

16

Insert 14 (non-AVL)

Step 1: Rotate child and grandchild


4
Double rotation

Step 2: Rotate node and new child (AVL)


4 2 1 3 6 7 15 16

4 2 1 3 5 7 14
9/27/01

2 1 3 5

6 7 15 14

15 16

14

16
Page 2 of 4

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 h +2

h +1

h +1 h +2

Apply a Single Rotation

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: B
Single rotation

D A h C h h +2 Double Rotation: B E h +1 A h

B E h +1 C h

F A h D G h C h OR h-1 OR h h +1 h h E A h
Double rotation

C h h-1

E h -1 OR h OR h

G h

h -1

h +2
9/27/01 Page 4 of 4

Potrebbero piacerti anche