Balanced tree lecture

Balanced trees

A binary tree's shape decides whether its operations are fast. This lecture makes that precise and motivates the problems around it.

Height drives cost

Search, insert, and delete on a binary search tree all walk a single root-to-leaf path, so they cost O(height). The question is: how tall is the tree?

  • A balanced tree of n nodes has height ≈ log₂(n). Operations are O(log n).
  • A degenerate tree (every node has one child) has height n − 1 — it's a glorified linked list, and operations degrade to O(n).
balanced (h≈2)        degenerate (h=3)
      4                   1
     / \                   \
    2   6                   2
   / \ / \                   \
  1  3 5  7                   3
                               \
                                4

Same values, wildly different performance.

What "balanced" means

A common, checkable definition: a tree is height-balanced if, for every node, the heights of its left and right subtrees differ by at most 1. Checking it naively (compute height at every node) is O(n²); computing height and the balanced-flag together in one post-order pass is O(n) — a trick the "Is Tree Balanced" problem rewards.

Self-balancing trees

Real libraries use self-balancing BSTs — AVL trees, red-black trees — that rotate nodes on insert/delete to keep the height O(log n) automatically. You won't implement one here, but knowing they exist explains why map/set libraries promise O(log n) (or O(1) for hash-based ones).

Takeaway: when someone says a tree operation is O(log n), they're assuming it's balanced. Shape is everything.