Balanced Trees (cont’d)
Week 10, Monday
March 9, 2026
AVL Tree Explorer
Rotations on a BST
Rotations on a BST
Operations on BSTs — Rotations
Rotation properties:
- There are 4 kinds: left, right, left-right, right-left
- Local operations (subtrees not affected)
- Constant time (\(O(1)\))
- BST property maintained
AVL Trees
GOAL: use rotations to maintain balance of BSTs.
These trees have a special name: AVL Trees
Named after Adelson-Velsky and Landis (1962).
AVL Property: For every node, \(|b| \leq 1\).
Three issues to consider in the implementation:
- Rotation
- Maintaining height
- Detecting imbalance
AVL Height is O(log n)
Theorem: An AVL tree with \(n\) nodes has height \(h = O(\log n)\).
Let \(N(h)\) denote the fewest nodes possible in an AVL tree of height \(h\).
- \(N(0) = 1\)
- \(N(1) = 2\)
- \(N(h) =\) ______________
Proof by Induction
Claim: \(N(h) \geq 2^{h/2}\)
Base cases: \(N(0) = 1 \geq 2^0 = 1\) ✓ and \(N(1) = 2 \geq 2^{1/2} \approx 1.41\) ✓
Inductive step (\(h \geq 2\)): Assume the claim holds for all \(j < h\).
\[N(h) = N(h-1) + N(h-2) + 1\]
Updated Dictionary Comparison
| Unsorted list |
O(1) |
O(n) |
O(n) |
O(n log n) |
| Sorted list |
O(n) |
O(log n) |
O(n) |
O(n) |
| Hash table |
O(1) avg |
O(1) avg |
O(1) avg |
Not possible |
| BST (unbalanced) |
O(n) worst |
O(n) worst |
O(n) worst |
O(n) |
| AVL tree |
O(log n) |
O(log n) |
O(log n) |
O(n) |
Balanced Trees in Practice
| C++ |
std::map, std::set (Red-Black) |
| Java |
TreeMap, TreeSet (Red-Black) |
| Python |
sortedcontainers.SortedDict (3rd party) |
| Databases |
B-trees, B+ trees |
Python’s built-in dict uses hash tables, not trees.
Summary: Balanced Trees
BST operations are O(height) — height matters!
Unbalanced BSTs can have O(n) height — bad for sorted input
Rotations reshape BSTs while preserving order
AVL trees use rotations to maintain \(|b| \leq 1\) for every node
Diagnosing: check child’s balance factor to pick the rotation
Guarantee: \(O(\log n)\) height, so \(O(\log n)\) operations
Practice
- Is this tree AVL-balanced? (Check every node’s balance factor)
50
/ \
30 70
/ / \
20 60 90
/
10
If not, which rotation(s) would fix it?
After inserting 5, 3, 7, 2, 4, 6, 8 into an empty AVL tree, what does it look like?
(Hint: Use the visualization tool to check!)