Docsity

AVL Trees - Data Structures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download AVL Trees - Data Structures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Lecture 12

AVL Trees

1

2

Types of Trees

trees

static dynamic

game trees search trees

priority queues

and heaps

graphs

binary search

trees

AVL trees

2-3 trees tries Huffman

coding

tree

AVL Trees

• Balanced binary search tree offer a O(log n) insert

and delete.

• But balancing itself costs O(n) in the average case.

• In this case, even though delete will be O(log n),

insert will be O(n).

• Is there any way to have a O(log n) insert too?

• Yes, by almost but not fully balancing the tree : AVL

(Adelson Velskii and Landis) balancing

4

Height of a Tree

• Definition is same as level. Height of a tree is the length of the

longest path from root to some leaf node.

• Height of a empty tree is -1.

• Height of a single node tree is 0.

• Recursive definition:

• height(t) = 0 if number of nodes = 1

= -1 if T is empty

= 1+ max(height(LT), height(RT)) otherwise

5

AVL Tree: Example

7

Non-AVL Tree

8

Transformations

• Single right :

((T1 + T2) + T3) = (T1 + (T2 + T3)

• Single left :

(T1 + (T2 + T3)) = ((T1 + T2) + T3)

• Double right :

((T1 + (T2 + T3)) + T4) = ((T1+T2) + (T3+T4))

• Double left :

(T1 ((T2+T3) +T4)) = ((T1+T2) + (T3+T4))

10

Example: AVL Tree for Airports

• Consider inserting sequentially : ORY, JFK, BRU,

DUS, ZRX, MEX, ORD, NRT, ARN, GLA, GCM

• Build a binary-search tree

• Build a AVL tree.

11

AVL Balancing : Four Rotations

13

  • X Single right
    • X - X - X - X1 X
  • X - X - X - X Single left - X3 X - X - X - X - X Double right - X2 X - X - X1 X - X - X - X

An AVL Tree for Airport Names

14

ORY
JFK
BRU

Not AVL balanced

Single right JFK

BRU
ORY

AVL Balanced

After insertion of ORY, JFK and BRU :

An AVL Tree …

16

JFK
BRU
ORY
DUS MEX
ZRH
ORD
NRT
Not AVL Balanaced
Double Left
JFK
BRU
ORY
DUS NRT
ZRH
MEX ORD
Now add ARN and GLA; no
need for rotations; Then add GCM

An AVL Tree…

17

JFK
BRU
DUS
ORY
NRT
ZRH
MEX ORD
ARN
GLA
GCM
NOT AVL BALANCED
JFK
BRU
GCM
ORY
NRT ZRH
MEX ORD
ARN
GLA
Double left
DUS

Known Performance Results of AVL trees

  • AVL tree is a sub optimal solution.
  • How to evaluate its performance?
  • Bounds (upper bound and lower bound) for number of comparisons: C > log(n+1) + 1 C < 1.44 log(n+2) - 0.
  • AVL trees are no more than 44% worse than optimal trees. 19

20