You are on page 1of 21

AVL Trees

AVL Trees
For some binary search tree, the height could be quite large, which is not good for searching.  An AVL tree is a binary search tree with a balance condition

 To

ensure that the height of the tree is O(logN)  For every node in the AVL tree, the height of left subtree and the height of the right subtree can differ by at most one.

AVL Trees


The height of the left subtree minus the height of the right subtree of a node is called the balance of the node. For an AVL tree, the balances of the nodes are always -1, 0 or 1.
 The

height of an empty tree is defined to be -1.

Given an AVL tree, if insertions or deletions are performed, the AVL tree may not remain height balanced.

AVL Trees
5 2 8 2 7 8

An AVL Tree

Not an AVL Tree

AVL Trees


To maintain the height balanced property of the AVL tree after insertion or deletion, it is necessary to perform a transformation on the tree so that (1) the inorder traversal of the transformed tree is the same as for the original tree (i.e., the new tree remains a binary search tree). (2) the tree after transformation is height balanced.

AVL Trees
After an insertion, only nodes that are on the path from the insertion point to the root might have their balance altered  Follow the path up to the root, find the first node (i.e., deepest) whose new balance violates the AVL condition. Call this node a.  Rebalance the tree at node a.  This guarantees that the entire tree is balanced.


AVL Trees
 Violation

may occur when an insertion into

1. left subtree of left child of a (LL case) 2. right subtree of left child of a (LR case) 3. left subtree of right child of a (RL case) 4. right subtree of right child of a (RR case)

AVL Trees
 Rotation

- to restore the AVL tree after insertion - single rotation


 For

case 1 and 4 case 2 and 3

- double rotation
 For

AVL Trees: Single Rotation


Example: 3 2 1 4 5 6 7  construct binary search tree without height balanced restriction  depth of tree = 4


i.e. LL case

AVL Trees: Single Rotation




Construct AVL tree (height balanced)

AVL Trees: Single Rotation


Insert 4, 5

Insert 6

AVL Trees: Single Rotation

Insert 7

AVL Trees: Double Rotation




Single rotation fails to fix cases 2 and 3 (i.e. LR and RL cases)

AVL Trees: Double Rotation


Double rotation is used  case 2 (LR case)


AVL Trees: Double Rotation




case 3 (RL case)

AVL Trees: Double Rotation




Example:

AVL Trees: Double Rotation




Insert 14

AVL Trees: Double Rotation




Insert 13 (This is single rotation: RR Case)

AVL Trees: Double Rotation




Insert 12

AVL Trees: Double Rotation




Insert 11 and 10 (single rotation), then 8

AVL Trees: Double Rotation




Inserting 9

You might also like