AVL Trees

COMP2521 20T2 ♢ AVL Trees [0/9]
❖ Better Balanced Binary Search Trees

So far, we have seen …

Ideally, we want both average/worst case to be O(log n)
COMP2521 20T2 ♢ AVL Trees [1/9]
❖ AVL Trees

Invented by Georgy Adelson-Velsky and Evgenii Landis   (1962)

Goal:

Approach:

COMP2521 20T2 ♢ AVL Trees [2/9]
❖ ... AVL Trees


A tree is unbalanced when   abs(height(left)-height(right)) > 1

This can be repaired by rotation:


Problem: determining height/depth of subtrees is expensive Solution: store balance data in each node  (either height or balance)
COMP2521 20T2 ♢ AVL Trees [3/9]
❖ AVL Tree Examples


Red numbers are height;   green numbers are balance


COMP2521 20T2 ♢ AVL Trees [4/9]
❖ ... AVL Tree Examples


How an unbalanced tree can be rebalanced


COMP2521 20T2 ♢ AVL Trees [5/9]
❖ AVL Insertion Algorithm

Implementation of AVL insertion

insertAVL(tree,item):
|  Input  tree, item
|  Output tree with item AVL-inserted
|
|  if tree is empty then
|     return new node containing item
|  else if item = data(tree) then
|     return tree
|  else
|  |  if item < data(tree) then
|  |     left(tree) = insertAVL(left(tree),item)
|  |  else if item > data(tree) then
|  |     right(tree) = insertAVL(right(tree),item)
|  |  end if
|  |  LHeight = height(left(tree))
|  |  RHeight = height(right(tree))
|  |  if (LHeight - RHeight) > 1 then
|  |     if item > data(left(tree)) then
|  |        left(tree) = rotateLeft(left(tree))
|  |     end if
|  |     tree=rotateRight(tree)
|  |  else if (RHeight - LHeight) > 1 then
|  |     if item < data(right(tree)) then
|  |        right(tree) = rotateRight(right(tree))
|  |     end if
|  |     tree=rotateLeft(tree)
|  |  end if
|  |  return tree
|  end if
COMP2521 20T2 ♢ AVL Trees [6/9]
❖ Maintaining Balance/Height


Store height in nodes; update on insertion; compute balance



If abs(balance) > 1 after updating, rebalance via rotation

COMP2521 20T2 ♢ AVL Trees [7/9]
❖ Searching AVL Trees

Exactly the same as for regular BSTs.

[Diagram:Pics/avl4.png]


Height/balance measures are ignored

COMP2521 20T2 ♢ AVL Trees [8/9]
❖ Performance of AVL Trees

Analysis of AVL trees:

COMP2521 20T2 ♢ AVL Trees [9/9]


Produced: 15 Jun 2020