Docsity

AVL Tree: Cases for Rotation and Insertion Algorithm, Slides of Data Structures and Algorithms

Partial preview of the text

Download AVL Tree: Cases for Rotation and Insertion Algorithm and more Slides Data Structures and Algorithms in PDF only on Docsity!

1

Cases for Rotation

 Single right rotation fails to fix case 2.

k 1

k 2

Z

X

Level n

Level n-

Level n-

k 1

k 2

Z

X

new

Y

new

Y

2

Cases for Rotation

 Y is non-empty because

the new node was inserted

in Y.

 Thus Y has a root and two

subtrees.

 View the entire tree with

four subtrees connected

with 3 nodes.

k 1

k 2

X

Y

Z

4

Cases for Rotation

k 3

k 1

A

new

1

2

New node inserted a either of the

two spots

B C

k 2

D

new’

 Exactly one of tree B or C

is two levels deeper than

D ; we are not sure which

one.

 Good thing: it does not

matter.

 To rebalance, k

3

cannot be

left as the root.

5

Cases for Rotation

k 3

k 1

A

new

1

2

New node inserted a either of the

two spots

B C

k 2

D

new’

 A rotation between k

and k

( k

was k

then)

was shown to not work.

 The only alternative is

to place k

as the new

root.

 This forces k

to be k

‘s

left child and k

to be

its right child.

7

Cases for Rotation

 Left-right double rotation to fix case 2.

A

new

B

D

C

A new’

new

B

D

C

new’

k 3

k 2

k 1

Rotate right

k 2

k 3

k 1

8

Cases for Rotation

 Right-left double rotation to fix case 3.

k 1

k 3

D

A

B C

k 2

k 1

k 3

D

A

B

C

k 2

Rotate right

10

AVL Tree Building Example

Insert(15)

X

(null)

Z

(null)

Y

k 1

k 2

11

AVL Tree Building Example

Insert(15) right-left double rotation

k 1

k 3

k 2

Rotate right

13

AVL Tree Building Example

Insert(15) right-left double rotation

k 3

k 2

k 1

14

AVL Tree Building Example

Insert(14): right-left double rotation

k 3

k 2

k 1

Rotate right

16

AVL Tree Building Example

Insert(14): right-left double rotation

k 3

k 2

k 1

17

AVL Tree Building Example

Insert(13): single rotation

Rotate left

19

C++ code for insert

TreeNode*

avlInsert(TreeNode root, int info)*

{

if( info < root->getInfo() ){

root->se tLeft(avlInsert(root->getLeft(), info));

int htdiff = height(root->getLeft()) –

height(root->getRight());

if( htdiff == 2 )

if( info < root->getLeft()->getInfo() )

root = singleRightRotation( root );

else

root = doubleLeftRightRotation( root );

}

20

C++ code for insert

TreeNode*

avlInsert(TreeNode root, int info)*

{

if( info < root->getInfo() ){

root->setLeft(avlInsert(root->getLeft(), info));

int htdiff = height(root->getLeft()) –

height(root->getRight());

if( htdiff == 2 )

if( info < root->getLeft()->getInfo() )

root = singleRightRotation( root );

else

root = doubleLeftRightRotation( root );

}