Sub topic 5
Building the Huffman Tree with a Min-Heap
This chapter assumes you know how binary trees work, how to traverse them recursively, and how a min-heap (priority queue) returns its smallest item. It also builds on the earlier chapters on symbol frequencies and binary code trees.
The Greedy Idea
Huffman's algorithm builds the code tree from the bottom up. Each symbol starts as a leaf with a weight equal to its frequency. The algorithm repeats one step: take the two lightest nodes and join them under a new parent whose weight is their sum. When only one node is left, that node is the root.
The rarest symbols get merged first, so they end up deepest in the tree and receive the longest codes. Frequent symbols are merged late, so they stay near the root and get short codes.
A min-heap fits this job because it returns the smallest weight in O(log n) time. With n symbols there are n − 1 merges, so the whole build takes O(n log n).
Tracing "abracadabra"
The frequencies are a:5, b:2, r:2, c:1, d:1.
| Step | Pop two lightest | New node weight | Heap afterwards |
|---|---|---|---|
| 1 | c:1, d:1 | 2 | a:5, b:2, r:2, (cd):2 |
| 2 | b:2, r:2 | 4 | a:5, (cd):2, (br):4 |
| 3 | (cd):2, (br):4 | 6 | a:5, (cdbr):6 |
| 4 | a:5, (cdbr):6 | 11 | root:11 |
The Code
import heapq
from collections import Counter
from itertools import count
def build_codes(text):
freq = Counter(text)
tiebreak = count()
heap = [(f, next(tiebreak), sym) for sym, f in freq.items()]
heapq.heapify(heap)
if len(heap) == 1:
_, _, sym = heap[0]
return {sym: "0"}
while len(heap) > 1:
f1, _, left = heapq.heappop(heap)
f2, _, right = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, next(tiebreak), (left, right)))
codes = {}
def walk(node, prefix):
if isinstance(node, tuple):
walk(node[0], prefix + "0")
walk(node[1], prefix + "1")
else:
codes[node] = prefix
walk(heap[0][2], "")
return codes
print(build_codes("abracadabra"))
# {'a': '0', 'c': '100', 'd': '101', 'b': '110', 'r': '111'}Each heap entry is a tuple (weight, tiebreak, node). A leaf is a plain symbol string. An internal node is a (left, right) pair. The walk function adds "0" when it goes left and "1" when it goes right, and records the path as the code when it reaches a leaf.
Common Errors
- Comparing nodes on ties. Python compares tuples one element at a time. Without the counter, two entries with equal weight would make Python compare a string with a tuple, which raises
TypeError. The counter values are unique, so the comparison never gets as far as the node. - Single-symbol input. For a text like
"aaaa", the loop never runs and the root is a leaf. Walking it would give an empty code, so the function returns"0"instead. - Expecting one correct answer. How ties are broken, and which child goes on the left, changes the actual bit patterns. Every result is still optimal, and the total encoded length stays the same.
- Forgetting
heapify. A plain list that is not in heap order givesheappopwrong results without raising any error.
Exercise
Build a Huffman tree by hand for the frequencies A:4, B:2, C:1, D:1. What code length does each symbol get, and how many bits does the whole message take?
Show answer
First merge C and D into a node of weight 2. Then merge B (2) with that node into weight 4. Finally merge A (4) with it into weight 8. The code lengths are A=1, B=2, C=3, D=3. The total is 4·1 + 2·2 + 1·3 + 1·3 = 14 bits.
Exercise
If you removed the tiebreak counter and stored heap entries as (weight, node), which input in this chapter would fail, and why?
Show answer
"abracadabra" would fail. After step 1 the heap holds b:2, r:2, and (cd):2, which all have weight 2. Python then compares the second elements, a string and a tuple, and raises TypeError.