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 = (min.) # nodes in height-h AVL tree
AVL insert
- simple BST insert
- fix AVL property
- suppose x is the lowest node violating AVL
- suppose x is right-heavy
- if x's right child is right heavy or balanced, LR(x)
- else RR(x), LR(x)