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 N_{h} = (min.) # nodes in height-h AVL tree

N_{h} = 1 + N_{h-1} + N_{h-2}

N_{h} > F_{h} = \frac{\phi ^{h}}{\sqrt{5}}

max. h \approx 1.440 lg n

 AVL insert

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

    Introduction to Algorithms (AVL Trees, AVL Sort)_第1张图片

     Introduction to Algorithms (AVL Trees, AVL Sort)_第2张图片

    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)

你可能感兴趣的:(Introduction to Algorithms (AVL Trees, AVL Sort))