PDSA Interactive Book
Week 7

Balanced Trees & Greedy Algorithms

Keeping trees balanced, and the art of making locally best choices.

After this chapter you can…
  • 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).

AVL property

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

Check yourself

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:

CaseShapeFix
Left–Leftnew key in left subtree of left childone right rotation at z
Right–Rightnew key in right subtree of right childone left rotation at z
Left–Rightnew key in right subtree of left childleft rotation at the child, then right rotation at z
Right–Leftnew key in left subtree of right childright rotation at the child, then left rotation at z
AVL tree — insert keys (try 10, 20, 30, 40, 50) and watch the rotationsInteractive
Python · editable
Expected output: [30, 20, 10, 25, 40, 50] height 3 1..15 inserted in order -> height 4
Costs

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.

Predict the output

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))
Predict the output

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))
Check yourself

After inserting 5, 4, 3 into an empty AVL tree (in this order), which key is the root?

Check yourself

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.

Greedy can fail

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

Greedy vs optimal change — try your own coinsInteractive
Python · editable
Expected output: [4, 1, 1] [25, 25, 10, 1, 1, 1]

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.

Python · editable
Expected output: [(1, 4), (5, 7), (8, 11), (12, 16)]
Interval scheduling — greedy by earliest finish timeInteractive
Why earliest finish is safe (exchange argument)

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

Predict the output

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))
Check yourself

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.

The cut property

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.

Python · editable
Expected output: ([(1, 3, 6), (2, 4, 8), (0, 1, 10), (1, 2, 20)], 44)

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.

Python · editable
Expected output: 44
Kruskal vs Prim — same tree, different orderInteractive
Graph lab — Kruskal and Prim on a graph you editInteractive
KruskalPrim
Growsa forest of many componentsa single tree
Key structuresorted edges + Union–Findpriority queue of boundary edges
TimeO(m log m)O(m log n)
Good forsparse graphs / edge listsdense graphs
Check yourself

Kruskal's algorithm skips an edge when…

Predict the output

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)
Check yourself

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.

Huffman tree — type your own textInteractive
Python · editable
Expected output: {'a': 1, 'b': 2, 'c': 3, 'd': 3} total bits: 25 vs fixed 2-bit: 30
Check yourself

A prefix-free code means…

Check yourself

In Huffman's algorithm, which two items are merged at each step?

Chapter challenge — Week 7

…
Check yourself

The AVL balance factor of a node is…

Predict the output

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))
Put in order

Kruskal's algorithm — put the steps in order.

Check yourself

Which problem is not solved optimally by the obvious greedy rule?

Check yourself

A connected graph has 9 vertices. How many edges does each of its spanning trees have?

Check yourself

Which statements are true?

Predict the output

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)
Check yourself

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.

How to practise

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.

0 / 11 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Convert Sorted Array to Binary Search Tree ↗Easybuild a balanced BST from the middle
Balanced Binary Tree ↗Easythe AVL height condition
Assign Cookies ↗Easyeasy greedy with sorting
Non-overlapping Intervals ↗Mediuminterval scheduling: sort by finish time
Minimum Number of Arrows to Burst Balloons ↗Mediuminterval greedy
Merge Intervals ↗Mediumsort, then sweep
Jump Game ↗Mediumgreedy reach
Gas Station ↗Mediumgreedy with a proof
Partition Labels ↗Mediumgreedy over last occurrences
Task Scheduler ↗Mediumgreedy with counts
Min Cost to Connect All Points ↗Mediumminimum 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.

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.