Class No.20 Data Structures http://ecomputernotes.com

AVL Tree AVL (Adelson-Velskii and Landis) tree. An AVL tree is identical to a BST except height of the left and right subtrees can differ by at most 1. height of an empty tree is defined to be (–1).

http://ecomputernotes.com

AVL Tree ď‚§ An AVL Tree

height 0

5 2

1

8

4

7

3

http://ecomputernotes.com

1

2 3

AVL Tree ď‚§ Not an AVL tree

height 0

6 1

1

8

4 3

1

2 5

http://ecomputernotes.com

3

Balanced Binary Tree The height of a binary tree is the maximum level of its leaves (also called the depth). The balance of a node in a binary tree is defined as the height of its left subtree minus height of its right subtree. Here, for example, is a balanced tree. Each node has an indicated balance of 1, 0, or –1. http://ecomputernotes.com

Balanced Binary Tree -1 1 0 0

0 -1

1

0 0

0 0

0 0

0

0 0

http://ecomputernotes.com

0

Balanced Binary Tree Insertions and effect on balance -1 1

0

0 0 U1

0 U2

U3

B

-1

1

0 0

B

0

U4 U5

0 U6

0

0

U7

B U8

B

B

0 B

0

U9

http://ecomputernotes.com

0 U10

U11

U12

Balanced Binary Tree Tree becomes unbalanced only if the newly inserted node is a left descendant of a node that previously had a balance of 1 (U1 to U8), or is a descendant of a node that previously had a balance of –1 (U9 to U12)

http://ecomputernotes.com

Balanced Binary Tree Insertions and effect on balance -1 1

0

0 0 U1

0 U2

U3

B

-1

1

0 0

B

0

U4 U5

0 U6

0

0

U7

B U8

B

B

0 B

0

U9

http://ecomputernotes.com

0 U10

U11

U12

Balanced Binary Tree Consider the case of node that was previously 1 -1 1

0

0 0 U1

0 U2

U3

B

-1

1

0 0

B

0

U4 U5

0 U6

0

0

U7

B U8

B

B

0 B

0

U9

http://ecomputernotes.com

0 U10

U11

U12

Inserting New Node in AVL Tree A 1

B 0 T3 T1

T2

1

http://ecomputernotes.com

Inserting New Node in AVL Tree A 2

B 1 T3 T1

T2

1 2

new

http://ecomputernotes.com

Inserting New Node in AVL Tree A 2

B 0

B 1

0 T1

T3 T1

1

T2

T2 2

new

new

Inorder: T1 B T2 A T3

A

Inorder: T1 B T2 A T3

http://ecomputernotes.com

T3

AVL Tree Building Example ď‚§ Let us work through an example that inserts numbers in a balanced search tree. ď‚§ We will check the balance after each insert and rebalance if necessary using rotations.

http://ecomputernotes.com

AVL Tree Building Example Insert(1) 1

http://ecomputernotes.com

AVL Tree Building Example Insert(2) 1 2

http://ecomputernotes.com

AVL Tree Building Example Insert(3) single left rotation 1

2

2

3

http://ecomputernotes.com

AVL Tree Building Example Insert(3) single left rotation 1

2

2

3

http://ecomputernotes.com

AVL Tree Building Example Insert(3) 2 1

3

http://ecomputernotes.com

computer notes - Data Structures - 20

Published on Dec 28, 2011

Class No.20 Data Structures AVL (Adelson-Velskii and Landis) tree. An AVL tree is identical to a BST except height of the left and right...

Advertisement

Read more

Similar to

Popular now

Just for you