Kodewick
Start learning →
Huffman trees and Huffman codes28 / 52

Huffman trees and Huffman codes

Lesson 28 of 52 · Part 5 · Trees and heaps · about 18 minutes

A Huffman tree is built by merging the two lightest trees again and again, with heapq handing over the two smallest, so frequent letters get short codes and rare ones long codes, read off as 0 for left and 1 for right.

A text of 100 letters uses only the six letters A to F. Store each in 3 bits (000 to 101) and it takes 300 bits. But if A appears 45 times and F only 5, give A 1 bit and F 4 bits, and the total can drop to 224 bits, a quarter saved. The question is how to share out the lengths so that the total is as small as possible, while a string of 0s and 1s can still be split back into letters unambiguously. Huffman answered it in 1952. The DEFLATE compression inside zip, gzip and PNG uses it as its last step.

Merge the two smallest, every time

Treat each letter as a tree of a single node, whose weight is how many times it appears. Then repeat one thing: take the two lightest trees and merge them into one, whose new root weighs the sum of the two, with the one taken first on the left. When only one tree is left, it is the Huffman tree.

A 45
C 12
B 13
F 5
E 9
D 16

A 45, B 13, C 12, D 16, E 9, F 5: merge the two lightest trees each time, building the whole tree from the bottom up

"Take out the two smallest, put one back": that is exactly last lesson's heap:

main.py
1import heapq2from itertools import count3 4class Node:5    def __init__(self, weight, ch=None, left=None, right=None):6        self.weight = weight7        self.ch = ch                       # only leaves have a letter8        self.left = left9        self.right = right10 11def huffman(freq):12    order = count()                        # 0, 1, 2, …: compared when weights tie13    h = [(w, next(order), Node(w, ch)) for ch, w in freq.items()]14    heapq.heapify(h)15    while len(h) > 1:16        w1, _, a = heapq.heappop(h)        # the smallest17        w2, _, b = heapq.heappop(h)        # the second smallest18        print("merge", w1, "+", w2, "=", w1 + w2)19        heapq.heappush(h, (w1 + w2, next(order), Node(w1 + w2, None, a, b)))20    return h[0][2]21 22freq = {"A": 45, "B": 13, "C": 12, "D": 16, "E": 9, "F": 5}23root = huffman(freq)24print(root.weight, root.left.ch, root.right.weight)
Output
merge 5 + 9 = 14
merge 12 + 13 = 25
merge 14 + 16 = 30
merge 25 + 30 = 55
merge 45 + 55 = 100
100 A 55

6 letters take 5 merges: each merge leaves one tree fewer, so n trees take n − 1. Each merge is two heappops and one heappush, O(log n) each, so building the tree is O(n log n) in all.

Choose one

Building a Huffman tree from the weights 2, 3, 4, 7, 8: which two are merged second?

Choose one

A Huffman tree built for 6 letters: how many nodes does it have in all?

Nodes can't be compared

Why does the heap hold three things, (weight, counter, node), rather than two, (weight, node)? Tuples compare from their first item and only look at the second when the first ties. When two weights are equal, two Node objects get compared, and Python has no idea which Node is larger:

main.py
1import heapq2 3class Node:4    def __init__(self, weight, ch=None, left=None, right=None):5        self.weight = weight6        self.ch = ch7        self.left = left8        self.right = right9 10h = []11try:12    for ch, w in [("A", 2), ("B", 1), ("C", 1)]:13        heapq.heappush(h, (w, Node(w, ch)))14        print("pushed", ch)15except TypeError as e:16    print(type(e).__name__ + ": B and C both weigh 1, so two Node objects get compared")
Output
pushed A
pushed B
TypeError: B and C both weigh 1, so two Node objects get compared

When C goes in, its weight 1 ties with B's, the heap has to compare (1, B's node) with (1, C's node), and it fails. Put a counter that keeps rising in the middle: equal weights then compare counters, which never tie, so nodes are never compared. As a bonus the result is repeatable: with equal weights, whatever went in first comes out first, and every run builds the same tree.

The heap holdsWhen weights tieResult
(w, node)compares two nodesTypeError
(w, ch, node)compares letters, but merged trees have no letternew trees need a made-up "name" too, easy to get wrong
(w, next(order), node)compares countersalways comparable, first in first out

Another way is to give Node an __lt__ (comparing weights), but then it is unclear which of two equal weights comes out first; the counter is clearer.

Choose one

If the heap only holds (weight, node) pairs, when do you get a TypeError?

Guess the outputA wrong guess is fine

The middle item of each tuple is a counter from count(). What does this print?

1from itertools import count2 3order = count()4a = (5, next(order), "x")5b = (5, next(order), "y")6c = (3, next(order), "z")7print(a < b, c < a, a[1], c[1])

Reading the codes: 0 for left, 1 for right

Walk from the root to each letter, writing 0 for a step left and 1 for a step right, and the path is its code. All the letters are on leaves, so no code is the start of another (a prefix code): reading a complete code always lands on a leaf, so it can't be confused with another letter.

main.py
1import heapq2from itertools import count3 4class Node:5    def __init__(self, weight, ch=None, left=None, right=None):6        self.weight = weight7        self.ch = ch8        self.left = left9        self.right = right10 11def huffman(freq):12    order = count()13    h = [(w, next(order), Node(w, ch)) for ch, w in freq.items()]14    heapq.heapify(h)15    while len(h) > 1:16        w1, _, a = heapq.heappop(h)17        w2, _, b = heapq.heappop(h)18        heapq.heappush(h, (w1 + w2, next(order), Node(w1 + w2, None, a, b)))19    return h[0][2]20 21def codes(node, prefix, out):22    if node.ch is not None:                # a leaf: the path walked is its code23        out[node.ch] = prefix24    else:25        codes(node.left, prefix + "0", out)26        codes(node.right, prefix + "1", out)27    return out28 29freq = {"A": 45, "B": 13, "C": 12, "D": 16, "E": 9, "F": 5}30table = codes(huffman(freq), "", {})31for ch in sorted(table):32    print(ch, freq[ch], table[ch])
Output
A 45 0
B 13 101
C 12 100
D 16 111
E 9 1101
F 5 1100
LetterCountFixed codeHuffman codeHuffman bits
A45000045 × 1 = 45
B1300110113 × 3 = 39
C1201010012 × 3 = 36
D1601111116 × 3 = 48
E910011019 × 4 = 36
F510111005 × 4 = 20
Total100300 bits224 bits
A fixed-length code gives every letter 3 bits, 300 bits in all; the Huffman code is short for frequent letters and long for rare ones, 224 bits in all

Decoding goes the other way: start at the root, go left on a 0 and right on a 1, and as soon as you reach a leaf, output its letter and go back to the root to read on.

100
A 45
55
25
C 12
B 13
30
14
F 5
E 9
D 16

Decoding 1101: 1 right, 1 right, 0 left, 1 right, and we are at the leaf E. Output E and go back to the root for the next bit
Choose one

With this section's code table (A 0, C 100, B 101, F 1100, E 1101, D 111), what does 1100110100 decode to?

Choose one

Which set of codes is not a prefix code?

Exercise 1

Read the codes off the tree

huffman is already written. Complete codes(node, prefix, out): at a leaf, record prefix as that letter's code; going left adds "0" to the prefix and going right adds "1".

It should print
[('A', '0'), ('B', '101'), ('C', '100'), ('D', '111'), ('E', '1101'), ('F', '1100')]
[('x', '10'), ('y', '11'), ('z', '0')]
exercise1.py
1import heapq2from itertools import count3 4class Node:5    def __init__(self, weight, ch=None, left=None, right=None):6        self.weight = weight7        self.ch = ch8        self.left = left9        self.right = right10 11def huffman(freq):12    order = count()13    h = [(w, next(order), Node(w, ch)) for ch, w in freq.items()]14    heapq.heapify(h)15    while len(h) > 1:16        w1, _, a = heapq.heappop(h)17        w2, _, b = heapq.heappop(h)18        heapq.heappush(h, (w1 + w2, next(order), Node(w1 + w2, None, a, b)))19    return h[0][2]20 21def codes(node, prefix, out):22    # a leaf (ch is not None): out[node.ch] = prefix; otherwise "0" for the left and "1" for the right23    return out24 25table = codes(huffman({"A": 45, "B": 13, "C": 12, "D": 16, "E": 9, "F": 5}), "", {})26print(sorted(table.items()))27table = codes(huffman({"x": 1, "y": 1, "z": 2}), "", {})28print(sorted(table.items()))
Output
Press Run or Ctrl+Enter
Exercise 2

Decode

Complete decode(root, bits): start at the root, go left on "0" and right on "1"; at a leaf, add its letter to the result and go back to the root. The tree is ready-made: A is 0, C is 100, B is 101, F is 1100, E is 1101, D is 111.

It should print
BEAC
ADDCAF
E
exercise2.py
1class Node:2    def __init__(self, weight, ch=None, left=None, right=None):3        self.weight = weight4        self.ch = ch5        self.left = left6        self.right = right7 8L = lambda ch: Node(0, ch)9root = Node(100, None, L("A"),10            Node(55, None,11                 Node(25, None, L("C"), L("B")),12                 Node(30, None, Node(14, None, L("F"), L("E")), L("D"))))13 14def decode(root, bits):15    out, node = [], root16    # each bit: 0 left, 1 right; when node.ch is not None, output it and send node back to root17    return "".join(out)18 19print(decode(root, "10111010100"))20print(decode(root, "011111110001100"))21print(decode(root, "1101"))
Output
Press Run or Ctrl+Enter

The weighted path length

Each letter's code length is its depth in the tree (how many steps from the root). The total bits = each letter's count × its depth, all added up. This number is the tree's weighted path length (WPL). The Huffman tree is the binary tree with the smallest WPL: the more often a letter is used, the shallower it sits.

There is an easier way to work it out: each merge puts every letter in both subtrees one level deeper, adding exactly the two trees' weights to the total. So the WPL = the sum of the weights of all the merged nodes: 14 + 25 + 30 + 55 + 100 = 224.

main.py
1import heapq2 3freq = {"A": 45, "B": 13, "C": 12, "D": 16, "E": 9, "F": 5}4code = {"A": "0", "B": "101", "C": "100", "D": "111", "E": "1101", "F": "1100"}5print("count × code length:", sum(freq[ch] * len(code[ch]) for ch in freq))6 7h = list(freq.values())8heapq.heapify(h)9merged = []10while len(h) > 1:11    w = heapq.heappop(h) + heapq.heappop(h)12    merged.append(w)13    heapq.heappush(h, w)14print("merged weights:", merged, sum(merged))15print("fixed 3 bits:", 3 * sum(freq.values()))
Output
count × code length: 224
merged weights: [14, 25, 30, 55, 100] 224
fixed 3 bits: 300

For the total alone, there is no need to build the tree at all: plain numbers in the heap will do.

Guess the outputA wrong guess is fine

Four letters appear 1, 1, 2 and 4 times. What are the total bits of the Huffman code, and of a fixed 2 bits per letter?

1import heapq2 3h = [1, 1, 2, 4]4heapq.heapify(h)5cost = 06while len(h) > 1:7    w = heapq.heappop(h) + heapq.heappop(h)8    cost += w9    heapq.heappush(h, w)10print(cost, 2 * sum([1, 1, 2, 4]))

In interviews: Huffman is the classic example of a greedy algorithm: each step only merges the two smallest at hand, yet the end result is the best overall. Typical questions: "Why is it a prefix code?" (the letters are all on leaves), "What does building it cost?" (n − 1 merges of O(log n) each, O(n log n) in all), "Is the Huffman tree unique?" (no: equal weights can swap left and right, but the WPL is always the same minimum).

Choose one

What is the weighted path length (WPL) of the Huffman tree for the weights 2, 3, 4, 7, 8?

How you write it at work

At work you don't write Huffman compression yourself: to compress data, use the standard library's zlib, gzip or zipfile, whose DEFLATE algorithm first finds repeated pieces and then applies Huffman coding. Writing it once is worth it for seeing heapq with a counter in action, and the whole road of "count frequencies → build the tree → encode → decode":

main.py
1import heapq2from collections import Counter3from itertools import count4 5class Node:6    def __init__(self, weight, ch=None, left=None, right=None):7        self.weight = weight8        self.ch = ch9        self.left = left10        self.right = right11 12def huffman(freq):13    order = count()14    h = [(w, next(order), Node(w, ch)) for ch, w in freq]15    heapq.heapify(h)16    while len(h) > 1:17        w1, _, a = heapq.heappop(h)18        w2, _, b = heapq.heappop(h)19        heapq.heappush(h, (w1 + w2, next(order), Node(w1 + w2, None, a, b)))20    return h[0][2]21 22def codes(node, prefix, out):23    if node.ch is not None:24        out[node.ch] = prefix or "0"       # with only one letter, it still needs 1 bit25    else:26        codes(node.left, prefix + "0", out)27        codes(node.right, prefix + "1", out)28    return out29 30text = "abracadabra"31freq = sorted(Counter(text).items())       # sorted: every run builds the same tree32root = huffman(freq)33table = codes(root, "", {})34print(freq)35print(sorted(table.items()))36 37bits = "".join(table[ch] for ch in text)38print(bits, len(bits), "bits; at 8 bits a letter it takes", 8 * len(text), "bits")39 40out, node = [], root41for b in bits:                             # decode: 0 left, 1 right, output at a leaf42    node = node.left if b == "0" else node.right43    if node.ch is not None:44        out.append(node.ch)45        node = root46print("".join(out) == text)
Output
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
[('a', '0'), ('b', '110'), ('c', '100'), ('d', '101'), ('r', '111')]
01101110100010101101110 23 bits; at 8 bits a letter it takes 88 bits
True
  • Count frequencies with collections.Counter; to get the same result every run, sorted them before building the tree.
  • The heap holds (weight, next(order), node): itertools.count() is a ready-made rising counter.
  • With a single letter the tree is a single node and the code is an empty string: give it "0" as a special case.
  • To decode, the code table (or each letter's count) must be stored as well; real compressed formats write it ahead of the data.
Guess the outputA wrong guess is fine

Before building the tree, a Counter counts how often each letter appears. What does this print?

1from collections import Counter2 3print(sorted(Counter("banana").items()))
Choose one

text is "aaaa", a single letter. Without the special case in codes, what is a's code?

Summary

Take-away

Huffman: merge the two smallest, every time

  • One tree per letter; merge the two lightest again and again: n − 1 merges, O(n log n)
  • The heap holds (weight, counter, node): equal weights compare counters, never nodes
  • From the root, 0 for left and 1 for right; a leaf's path is its code; letters are all on leaves, so it is a prefix code
  • Total bits = sum of count × depth = sum of the merged weights, the smallest of any binary tree
1h = [(w, next(order), Node(w, ch)) for ch, w in freq.items()]2heapq.heapify(h)3while len(h) > 1:4    w1, _, a = heapq.heappop(h); w2, _, b = heapq.heappop(h)5    heapq.heappush(h, (w1 + w2, next(order), Node(w1 + w2, None, a, b)))