Introduction to Algorithms (AVL Trees, AVL Sort)

Recall: Binary Search Trees

  • rooted binary tree
  • each node has:
    • key
    • left pointer
    • right pointer
    • parent pointer
  • BST property
  • the height of node = length of the longest downward path to a leaf

The importance of being balanced

  • BSTs support insert, delete, min, max, next-larger, next-smaller, etc. in O(h) time, where h = height of the tree (= height of root).
  • keep BST small <=> keep the height of BST small <=> keep BST balanced 

AVL Trees

requires heights of left & right children of every node to differ by at most ±1

  • treat nil tree as height - 1
  • each node stores its height (DATA STRUCTURE AUGMENTATION) (like subtree size) (alternatively, can just store the difference in heights)

Balance

Worst when every node differs by 1

let Introduction to Algorithms (AVL Trees, AVL Sort) = (min.) # nodes in height-h AVL tree

Introduction to Algorithms (AVL Trees, AVL Sort)

Introduction to Algorithms (AVL Trees, AVL Sort)

Introduction to Algorithms (AVL Trees, AVL Sort)

 AVL insert

  1. simple BST insert
  2. fix AVL property ​​​​

    Introduction to Algorithms (AVL Trees, AVL Sort)

     Introduction to Algorithms (AVL Trees, AVL Sort)

    1. suppose x is the lowest node violating AVL
    2. suppose x is right-heavy
    3. if x's right child is right heavy or balanced, LR(x)
    4. else RR(x), LR(x)