Balanced Trees (cont’d)

Week 10, Monday

March 9, 2026

AVL Tree Explorer

Rotations on a BST

70 40 80 20 50 60

Rotations on a BST

70 40 80 20 50 60

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:

  1. Rotation
  2. Maintaining height
  3. 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

Structure Insert Find Delete Sorted Iterate
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

Language Balanced Tree
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

  1. BST operations are O(height) — height matters!

  2. Unbalanced BSTs can have O(n) height — bad for sorted input

  3. Rotations reshape BSTs while preserving order

  4. AVL trees use rotations to maintain \(|b| \leq 1\) for every node

  5. Diagnosing: check child’s balance factor to pick the rotation

  6. Guarantee: \(O(\log n)\) height, so \(O(\log n)\) operations

Practice

  1. Is this tree AVL-balanced? (Check every node’s balance factor)
        50
       /  \
      30   70
     /    /  \
    20   60   90
   /
  10
  1. If not, which rotation(s) would fix it?

  2. 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!)