Docsity

AVL Trees: Balanced Binary Search Trees, Slides of Data Structures and Algorithms

Partial preview of the text

Download AVL Trees: Balanced Binary Search Trees and more Slides Data Structures and Algorithms in PDF only on Docsity!

1

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).

2

AVL Tree

 An AVL Tree

height

4

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.

5

Balanced Binary Tree

7

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 (U

1

to U

8

 or is a descendant of a node that previously

had a balance of –1 (U

9

to U

12

8

Balanced Binary Tree

Insertions and effect on balance

U

1

U

2

U

3

U

4

U

5

U

6

U

7

U

8

U

9

U

10

U

11

U

12

B B B B

B B

10

Inserting New Node in AVL Tree

A

B

T

1

T

3

T

2

1

11

Inserting New Node in AVL Tree

A

B

T

1

T

3

T

2

new

1

2

13

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.

14

AVL Tree Building Example

Insert(1)

16

AVL Tree Building Example

Insert(3) single left rotation

-

17

AVL Tree Building Example

Insert(3) single left rotation

-