Balanced Trees & Greedy Algorithms
Keeping trees balanced, and the art of making locally best choices.
- explain the AVL property and apply the four rotation cases
- design and justify a greedy algorithm using an exchange argument
- run Kruskal's and Prim's algorithms by hand
- build a Huffman code from frequencies
Why balance a search tree?
Every BST operation costs O(height). Insert sorted data and the height becomes n. We want a tree whose height is always O(log n) — a balanced tree. The classic solution is the AVL tree (Adelson-Velsky and Landis, 1962).
For every node, the heights of its left and right subtrees differ by at most 1. The balance factor height(left) − height(right) is therefore −1, 0 or +1 everywhere.
An AVL tree with n nodes has height at most about 1.44 log₂ n. The sparsest AVL tree of height h has N(h) = N(h−1) + N(h−2) + 1 nodes — a Fibonacci-like recurrence that grows exponentially, so h = O(log n).
Which is an AVL tree?
Rotations — restoring balance locally
After an insert, some node on the path back to the root may reach balance factor ±2. A rotation rearranges a few pointers to reduce the height while preserving the BST order. There are four cases, according to where the new key went relative to the unbalanced node z:
| Case | Shape | Fix |
|---|---|---|
| Left–Left | new key in left subtree of left child | one right rotation at z |
| Right–Right | new key in right subtree of right child | one left rotation at z |
| Left–Right | new key in right subtree of left child | left rotation at the child, then right rotation at z |
| Right–Left | new key in left subtree of right child | right rotation at the child, then left rotation at z |
A rotation is O(1). An insert walks down O(log n) and fixes up O(log n) nodes (and in fact needs at most one single or double rotation). Deletion may need rotations at several levels, but still O(log n) total. So search, insert and delete are all O(log n) worst case.
Insert 30, 20, 10 into an AVL tree. What is the preorder (root, left, right)?
class Node:
def __init__(self, k):
self.k, self.l, self.r, self.h = k, None, None, 1
def ht(t):
return t.h if t else 0
def fix(t):
t.h = 1 + max(ht(t.l), ht(t.r))
def rot_right(y): # left child x becomes the root
x = y.l
y.l, x.r = x.r, y
fix(y); fix(x)
return x
def rot_left(x): # right child y becomes the root
y = x.r
x.r, y.l = y.l, x
fix(x); fix(y)
return y
def insert(t, k):
if t is None:
return Node(k)
if k < t.k:
t.l = insert(t.l, k)
elif k > t.k:
t.r = insert(t.r, k)
else:
return t
fix(t)
bal = ht(t.l) - ht(t.r)
if bal > 1: # left-heavy
if ht(t.l.l) < ht(t.l.r): # left-right case
t.l = rot_left(t.l)
return rot_right(t)
if bal < -1: # right-heavy
if ht(t.r.r) < ht(t.r.l): # right-left case
t.r = rot_right(t.r)
return rot_left(t)
return t
def preorder(t):
return [t.k] + preorder(t.l) + preorder(t.r) if t else []
root = None
for k in [30, 20, 10]:
root = insert(root, k)
print(preorder(root))Insert 10, 30, 20. What is the preorder now?
class Node:
def __init__(self, k):
self.k, self.l, self.r, self.h = k, None, None, 1
def ht(t):
return t.h if t else 0
def fix(t):
t.h = 1 + max(ht(t.l), ht(t.r))
def rot_right(y): # left child x becomes the root
x = y.l
y.l, x.r = x.r, y
fix(y); fix(x)
return x
def rot_left(x): # right child y becomes the root
y = x.r
x.r, y.l = y.l, x
fix(x); fix(y)
return y
def insert(t, k):
if t is None:
return Node(k)
if k < t.k:
t.l = insert(t.l, k)
elif k > t.k:
t.r = insert(t.r, k)
else:
return t
fix(t)
bal = ht(t.l) - ht(t.r)
if bal > 1: # left-heavy
if ht(t.l.l) < ht(t.l.r): # left-right case
t.l = rot_left(t.l)
return rot_right(t)
if bal < -1: # right-heavy
if ht(t.r.r) < ht(t.r.l): # right-left case
t.r = rot_right(t.r)
return rot_left(t)
return t
def preorder(t):
return [t.k] + preorder(t.l) + preorder(t.r) if t else []
root = None
for k in [10, 30, 20]:
root = insert(root, k)
print(preorder(root))After inserting 5, 4, 3 into an empty AVL tree (in this order), which key is the root?
A BST of 1000 keys inserted in sorted order has height 1000. The same keys inserted into an AVL tree give a height of about…
Greedy algorithms
A greedy algorithm builds a solution step by step, always taking the choice that looks best right now, and never reconsidering. When it works it is simple and fast. The skill is knowing when it works: usually you must prove a greedy-choice property (some optimal solution contains the greedy choice) via an exchange argument.
Make change for 6 with coins {1, 3, 4}. Greedy takes 4, then 1, then 1 = 3 coins. The optimum is 3 + 3 = 2 coins. For the coins {1, 5, 10, 25} greedy happens to work — but it is not true in general. (Those cases need dynamic programming — Week 9.)
Interval scheduling
Problem. Many activities each need a room during an interval [start, end). Choose the largest number of mutually non-overlapping activities.
Tempting greedy rules: earliest start (bad — one long early activity blocks everyone), shortest duration (bad — a short activity in the middle can block two others). The rule that works: always pick the compatible activity that finishes earliest.
Take any optimal schedule. Replace its first activity by the activity g that finishes earliest. g ends no later than the original did, so it cannot overlap anything else in the schedule. The count is unchanged, so an optimal solution containing g exists. Repeat on the remaining compatible activities.
Running time: dominated by the sort, O(n log n).
How many activities does the earliest-finish greedy choose?
acts = [(1, 3), (2, 5), (4, 7), (6, 9), (8, 10)]
chosen, last = [], 0
for s, e in sorted(acts, key=lambda a: a[1]):
if s >= last:
chosen.append((s, e))
last = e
print(len(chosen))Which greedy rule is the correct one for maximising the number of scheduled activities?
Minimum spanning trees
A spanning tree of a connected graph is a subgraph that connects all n vertices using exactly n − 1 edges (no cycles). Given edge weights, a minimum spanning tree (MST) has the least total weight — think cheapest cabling to connect all offices. Two greedy algorithms find it.
For any way of splitting the vertices into two non-empty groups, the cheapest edge crossing the split belongs to some MST (to all MSTs if weights are distinct). Both algorithms below are just clever ways of repeatedly picking such an edge.
Kruskal's algorithm — grow a forest
Sort the edges by weight. Scan them in increasing order; accept an edge if its endpoints are in different components (use Union–Find), otherwise skip it because it would form a cycle. Time: O(m log m) for sorting, plus near-constant union–find work.
Prim's algorithm — grow one tree
Start from any vertex. Repeatedly add the cheapest edge leaving the current tree (use a heap). Like Dijkstra, but it compares just the edge weight rather than a path length. Time: O(m log n) with a heap.
| Kruskal | Prim | |
|---|---|---|
| Grows | a forest of many components | a single tree |
| Key structure | sorted edges + Union–Find | priority queue of boundary edges |
| Time | O(m log m) | O(m log n) |
| Good for | sparse graphs / edge lists | dense graphs |
Kruskal's algorithm skips an edge when…
What is the weight of the minimum spanning tree?
edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4)]
p = list(range(4))
def find(x):
while p[x] != x:
x = p[x]
return x
total = 0
for u, v, w in sorted(edges, key=lambda e: e[2]):
a, b = find(u), find(v)
if a != b:
p[a] = b
total += w
print(total)A spanning tree of a connected graph with 12 vertices has how many edges?
Huffman coding — greedy compression
Fixed-length codes spend the same number of bits on every symbol, but some symbols are much more frequent than others. A prefix-free variable-length code gives frequent symbols short codewords (no codeword is a prefix of another, so decoding is unambiguous).
Huffman's algorithm: put each symbol in a heap by frequency. Repeatedly remove the two least frequent items and merge them into a new node whose frequency is the sum; stop when one tree remains. Left edges are 0, right edges are 1. The codeword of a symbol is its root-to-leaf path.
A prefix-free code means…
In Huffman's algorithm, which two items are merged at each step?
Chapter challenge — Week 7
The AVL balance factor of a node is…
What does this program print?
class Node:
def __init__(self, k):
self.k, self.l, self.r, self.h = k, None, None, 1
def ht(t):
return t.h if t else 0
def fix(t):
t.h = 1 + max(ht(t.l), ht(t.r))
def rot_right(y): # left child x becomes the root
x = y.l
y.l, x.r = x.r, y
fix(y); fix(x)
return x
def rot_left(x): # right child y becomes the root
y = x.r
x.r, y.l = y.l, x
fix(x); fix(y)
return y
def insert(t, k):
if t is None:
return Node(k)
if k < t.k:
t.l = insert(t.l, k)
elif k > t.k:
t.r = insert(t.r, k)
else:
return t
fix(t)
bal = ht(t.l) - ht(t.r)
if bal > 1: # left-heavy
if ht(t.l.l) < ht(t.l.r): # left-right case
t.l = rot_left(t.l)
return rot_right(t)
if bal < -1: # right-heavy
if ht(t.r.r) < ht(t.r.l): # right-left case
t.r = rot_right(t.r)
return rot_left(t)
return t
def preorder(t):
return [t.k] + preorder(t.l) + preorder(t.r) if t else []
root = None
for k in [1, 2, 3, 4, 5, 6, 7]:
root = insert(root, k)
print(preorder(root), ht(root))Kruskal's algorithm — put the steps in order.
Which problem is not solved optimally by the obvious greedy rule?
A connected graph has 9 vertices. How many edges does each of its spanning trees have?
Which statements are true?
What does this print? (type the exact output)
acts = [(0, 3), (2, 4), (3, 6), (5, 8), (7, 9)]
last, n = 0, 0
for s, e in sorted(acts, key=lambda a: a[1]):
if s >= last:
n += 1
last = e
print(n)Which has the best worst-case time for n lookups-plus-inserts on sorted input: plain BST, or AVL tree?
Practice on LeetCode
Balanced trees, greedy choices and minimum spanning trees.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Convert Sorted Array to Binary Search Tree ↗ | Easy | build a balanced BST from the middle | |
| Balanced Binary Tree ↗ | Easy | the AVL height condition | |
| Assign Cookies ↗ | Easy | easy greedy with sorting | |
| Non-overlapping Intervals ↗ | Medium | interval scheduling: sort by finish time | |
| Minimum Number of Arrows to Burst Balloons ↗ | Medium | interval greedy | |
| Merge Intervals ↗ | Medium | sort, then sweep | |
| Jump Game ↗ | Medium | greedy reach | |
| Gas Station ↗ | Medium | greedy with a proof | |
| Partition Labels ↗ | Medium | greedy over last occurrences | |
| Task Scheduler ↗ | Medium | greedy with counts | |
| Min Cost to Connect All Points ↗ | Medium | minimum spanning tree (Kruskal or Prim) |
Key takeaways
- AVL trees keep |height(left) − height(right)| ≤ 1 at every node using single/double rotations, so height is O(log n) and every operation is O(log n) worst case.
- Greedy = take the locally best choice and never undo it. It is only correct when you can prove the greedy-choice property (exchange argument) — coin change with arbitrary coins is a counter-example.
- Interval scheduling: sort by finish time, take every compatible interval. O(n log n).
- MST: Kruskal (sort edges + Union–Find) and Prim (grow a tree with a heap) both rely on the cut property.
- Huffman coding merges the two rarest symbols repeatedly, giving an optimal prefix-free code.