How Huffman coding merges the two lightest trees

Short answer: Huffman coding builds a prefix-free binary code by repeatedly merging the two lowest-frequency symbols, or trees, into a parent whose frequency is their sum. One child edge is bit 0 and the other is bit 1. The code for a symbol is the path from the root. The total encoded length is the weighted external path length, and no other prefix-free binary code has a smaller one for those frequencies. With a heap, the construction is O(n log n).


What the problem actually asks

A prefix-free code lets a decoder read bits until the bits form a codeword, with no separator. Among such codes, the frequent symbols should have the short words. Shannon-Fano splits the multiset from the top and does not always hit the optimum. Huffman’s rule grows the tree from the bottom by combining the two symbols that are currently cheapest to extend, and that greedy choice is optimal.

The proof is an exchange argument. Some optimal tree gives its two deepest leaves to the two rarest symbols. Merging those two symbols into a super symbol and solving the smaller problem produces the rest of the tree.


What the algorithm guarantees

The algorithm returns an optimal prefix-free binary code for a given multiset of positive frequencies. Time is O(n log n) with a binary heap, or O(n) if the frequencies are presorted and a queue holds the newly created parents. Extra memory is the tree. The code is not unique when frequencies tie, and different tie breaks change the words and not the optimal length. A symbol of frequency zero should be omitted. Including it spends a codeword on nothing.

The tree is not necessarily balanced. A skewed frequency list produces a long code for the rarest symbol, which is what optimality asks for. Canonical Huffman codes reshuffle the same lengths into a deterministic bit pattern so the decoder can store lengths instead of an arbitrary tree.


The working steps

  1. Put each symbol in its own node, weighted by its frequency, into a min-heap.
  2. While more than one node remains, pop the two lightest nodes. Create a parent with weight equal to the sum, attach the two nodes as children, and push the parent.
  3. The last node is the root. Label left edges 0 and right edges 1, or the reverse, consistently.
  4. The codeword of a symbol is the sequence of labels on the path from the root to its leaf.
  5. Decode by walking from the root according to the next bit, and emitting a symbol whenever the walk reaches a leaf, then returning to the root.

Optimality is among prefix-free binary codes for a known frequency table. It does not beat arithmetic coding, which can assign a fractional number of bits and approaches the entropy more tightly. It does not compress a string whose frequencies were never counted. Adaptive Huffman updates the tree as symbols arrive and is a different procedure.


Approaches that look simpler and fail

Approach Why it fails when the two lightest nodes are not the ones merged
Split the sorted list in half, as in Shannon-Fano The code is prefix-free and not always optimal. Huffman’s merge is the greedy step that the optimality proof uses.
Merge the two heaviest symbols first Frequent symbols then sit deep in the tree and receive long codes, which is the opposite of the objective.
Encode with the tree and omit the escape for the end of the stream A prefix-free code frames codewords inside the stream and does not by itself mark the end of the message. The container still needs a length or a terminator.
Use character frequencies from a different file The tree is optimal for the frequencies it was given. A mismatched model can expand the message.

A top-down split of the probability mass is Shannon-Fano. Fractional bit assignments are arithmetic coding. Dictionary compression, which encodes repeated strings rather than independent symbols, is LZ77 or LZW.


A working example

This Python fragment merges the two lightest trees until one tree remains. Symbols with weights 5, 9, 12, 13, 16, 45 get code lengths whose weighted sum is 224.

import heapq
weights = [("a", 5), ("b", 9), ("c", 12), ("d", 13), ("e", 16), ("f", 45)]
heap = [(w, i, {name: ""}) for i, (name, w) in enumerate(weights)]
heapq.heapify(heap)
counter = len(heap)
while len(heap) > 1:
    w1, _, c1 = heapq.heappop(heap)
    w2, _, c2 = heapq.heappop(heap)
    merged = {k: "0" + v for k, v in c1.items()}
    merged.update({k: "1" + v for k, v in c2.items()})
    heapq.heappush(heap, (w1 + w2, counter, merged))
    counter += 1
codes = heap[0][2]
by = dict(weights)
total = sum(by[name] * len(code) for name, code in codes.items())
assert total == 224 and len(set(codes.values())) == 6
print(total)

Where it is used

DEFLATE, the compressor in gzip, ZIP, and PNG, ends with a Huffman code of the LZ77 symbols. JPEG Huffman-codes DCT coefficients the same way. Shannon-Fano is the older split DEFLATE does not use.


When you can drop this algorithm

Drop Huffman coding when the model is not a single symbol distribution, or when a standard container such as DEFLATE already applies it after LZ77. Keep it when a prefix-free code for known symbol frequencies is the requirement and optimality among those codes matters.


Why this stays published

We publish this so a search for Huffman coding returns the repeated merge of the two lightest trees and the prefix-free optimality that merge has. Huffman coding builds an optimal prefix-free binary code by always merging the two lowest-frequency trees, in O(n log n) time with a heap.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *