Sub topic 5
Building the Huffman Tree with a Min-Heap
This chapter turns symbol frequencies into an actual Huffman tree. It assumes you can read Python, know how a binary tree is traversed recursively, and know what a min-heap does: it always gives back its smallest item first. It also builds on the earlier chapters on frequency counting, prefix-free codes, and code trees.
The greedy idea
Huffman's algorithm builds the code tree from the bottom up. Every symbol starts as its own one-node tree, weighted by its frequency. The algorithm then repeats one step:
- Remove the two trees with the smallest weights.
- Make them the left and right children of a new internal node.
- Give the new node the sum of their weights and put it back.
When only one tree is left, that tree is the Huffman tree. Each left edge is labeled 0 and each right edge 1. A symbol's code is the sequence of edge labels on the path from the root down to its leaf.
The reasoning is that a symbol's code length equals its depth in the tree. Rare symbols should end up deep and frequent ones shallow. Merging the two rarest trees first pushes them one level deeper than everything else. Every later merge pushes them deeper still, while the frequent symbols wait near the top. A later chapter proves that this greedy choice is optimal. Here the focus is on how it works.
A min-heap fits this job well. Each round needs "give me the smallest" twice and "insert" once, and a heap does each of those in O(log n) time.
Tracing it by hand
Take abracadabra. The frequencies are a:5, b:2, r:2, c:1, d:1. The table below shows the heap before each merge. Ties are broken by insertion order, which is what the code later in this chapter does.
| Step | Heap contents (weight: tree) | Pop two smallest | New node |
|---|---|---|---|
| 1 | 5:a, 2:b, 2:r, 1:c, 1:d | 1:c, 1:d | 2:(c,d) |
| 2 | 5:a, 2:b, 2:r, 2:(c,d) | 2:b, 2:r | 4:(b,r) |
| 3 | 5:a, 2:(c,d), 4:(b,r) | 2:(c,d), 4:(b,r) | 6:((c,d),(b,r)) |
| 4 | 5:a, 6:((c,d),(b,r)) | 5:a, 6:(...) | 11:root |
Five symbols need four merges. In general, n symbols always take exactly n − 1 merges, because each merge turns two trees into one.
Reading paths from the root gives a=0, c=100, d=101, b=110, r=111. The encoded length is 5×1 + 1×3 + 1×3 + 2×3 + 2×3 = 23 bits. Plain 8-bit characters would need 88.
The implementation
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"))Output:
{'a': '0', 'c': '100', 'd': '101', 'b': '110', 'r': '111'}How the pieces fit
- Heap entries are triples
(weight, tiebreak, tree). Python compares tuples one element at a time, so the heap orders entries by weight first. - Trees are stored in a compact form. A leaf is the symbol itself, a one-character string. An internal node is a 2-tuple
(left, right). Building with(left, right)makes the first popped item the0branch. heapifyturns the list into a heap in O(n) time, which is cheaper than n separate pushes.- The loop does the n − 1 merges. Each round costs O(log n), so the whole build is O(n log n).
walkis a preorder traversal. It adds"0"going left and"1"going right, and it records the prefix when it reaches a leaf.
Why the tie-breaker exists
A common bug is to push (weight, tree) pairs with no middle element. That works until two entries have equal weight. Python then compares the second elements, and those can be a string and a tuple:
try:
print((2, "b") < (2, ("c", "d")))
except TypeError as e:
print("TypeError:", e)TypeError: '<' not supported between instances of 'str' and 'tuple'In step 3 of the trace, 2:b, 2:r and 2:(c,d) all sit in the heap together, so this crash would happen on the very first example. The itertools.count() value is unique for every entry. Comparisons therefore never get past the second element, and Python never compares trees.
The counter has a second benefit: the result is deterministic. Ties resolve in a fixed order, oldest entry first, so the same input always gives the same codes. That matters when encoder and decoder must agree, and when tests compare exact output.
Ties produce different trees, not different costs
Suppose step 3 had popped 2:(c,d) and 2:b instead of 2:b and 2:r. That choice is just as valid, and it produces a different tree:
| Symbol | Freq | Length (trace above) | Length (alternative tie choice) |
|---|---|---|---|
| a | 5 | 1 | 1 |
| b | 2 | 3 | 3 |
| r | 2 | 3 | 2 |
| c | 1 | 3 | 4 |
| d | 1 | 3 | 4 |
| **Total bits** | **23** | **23** |
Both trees are optimal, and they have the same total cost. Their shapes differ: the second tree is deeper, with a maximum length of 4 instead of 3. This has two practical effects:
- Don't test a Huffman implementation by comparing exact codes against another library. Compare total encoded length, or check that the code lengths satisfy the Kraft equality (the sum of 2^−length equals 1).
- When a format limits the maximum code length, tie-breaking affects whether a tree fits. The chapter on length-limited codes covers this. A common tactic is to break ties in favor of the shallower subtree.
Edge cases and gotchas
A single distinct symbol
For input like "aaaa", the heap starts with one entry and the loop never runs. Without the special case, walk would reach the root leaf with an empty prefix and assign the code "". An empty code cannot be written to a bitstream, and nothing would tell the decoder how many symbols there are. The function assigns "0" instead, which spends one bit per symbol.
Empty input
build_codes("") creates an empty heap. It skips both the special case and the loop, then fails on heap[0] with an IndexError. A real encoder should check for empty input first and write an empty stream, or a header that says "zero symbols".
Symbols that are tuples
walk tells leaves apart from internal nodes with isinstance(node, tuple). That works for characters and bytes. If your symbols are themselves tuples, such as (length, distance) pairs, every leaf will look like an internal node. In that case, use a small Node class or wrap leaves explicitly.
Recursion depth
The deepest possible tree has depth n − 1. This happens when the frequencies grow like Fibonacci numbers (1, 1, 2, 3, 5, 8, ...). Python's default recursion limit is about 1000, so a 256-symbol byte alphabet is safe. A very large alphabet with skewed counts could overflow the stack. An explicit stack in place of recursion removes that limit.
Linear-time construction
If the frequencies are already sorted, you can skip the heap. Keep two FIFO queues: one holds the sorted leaves, and the other holds merged nodes in the order they are created. Merged weights never decrease, so the smallest item is always at the front of one queue or the other. Building the tree then takes O(n). For byte alphabets the difference is negligible, but the technique shows up in performance-tuned encoders.
Common errors checklist
| Symptom | Likely cause |
|---|---|
| `TypeError` comparing `str` and `tuple` | No unique tie-breaker in heap entries |
| Code `""` for a symbol | Single-symbol input not special-cased |
| `IndexError` on `heap[0]` | Empty input not handled |
| Codes differ from another tool | Different tie-breaking; compare total bits instead |
| Leaf symbols vanish from `codes` | Symbols are tuples and get treated as internal nodes |
Exercise
Build a Huffman tree by hand for the frequencies A:45, B:13, C:12, D:16, E:9, F:5. List the merges in order, give each symbol's code length, and compute the total encoded size in bits.
Show answer
Merges: F(5)+E(9)=14; C(12)+B(13)=25; 14+D(16)=30; 25+30=55; A(45)+55=100. Code lengths: A=1, B=3, C=3, D=3, E=4, F=4. Total = 45·1 + 13·3 + 12·3 + 16·3 + 9·4 + 5·4 = 45 + 39 + 36 + 48 + 36 + 20 = 224 bits. A fixed 3-bit code would need 300.
Exercise
An alphabet has 200 distinct symbols. How many times does the while loop in build_codes run, and what is the largest number of entries the heap ever holds?
Show answer
The loop runs 199 times, because each merge removes two entries and adds one, and the loop stops when one remains. The heap is largest right after heapify, with 200 entries. After that, every iteration shrinks it by one.
Exercise
A colleague changes heap entries to (f, sym) for leaves and (f, "", (left, right)) for internal nodes to "avoid the counter". Name two problems with this.
Show answer
First, the tuples now have different lengths and different element types at index 1. When a leaf and an internal node tie on weight, Python compares sym with "" (which works), but two internal nodes that tie on weight both have "" at index 1, so Python compares their trees and can raise a TypeError. Second, ties no longer resolve in a stable, documented order, so the output may change with small changes to the input order. A unique, increasing counter fixes both problems.