Kodewick
Start learning →
Huffman trees and Huffman codes28 / 52

Huffman trees and Huffman codes

Lesson 28 of 52 · Part 5 · Trees · about 16 minutes

A Huffman tree repeatedly merges the two smallest weights, and 0 for left, 1 for right gives codes of the smallest total length, none the start of another, so decoding is never ambiguous; C++ builds it with a priority_queue.

A text of 100 characters uses only 6 letters, A to F. Storing each in 3 bits (000 to 101) takes 300 bits. But if A appears 45 times and F only 5, giving A 1 bit and F 4 bits cuts the total a lot. The question: how to hand out the lengths so the total is smallest, and decoding can still tell them apart? Huffman answered it in 1952.

Merge the two smallest, again and again

Treat each letter as a tree of one node, weighted by how often it appears. Then do one thing over and over: take the two trees with the smallest weights and merge them into a new tree, whose root weighs the two together. When one tree is left, it's 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 smallest each time, building the whole tree from the bottom up

"Take the two smallest, put one back" is exactly what last lesson's priority queue does: with a min-heap, each round is two pops and one push, and n letters take n − 1 rounds, O(n log n).

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?

The codes: 0 to the left, 1 to the right

Walk from the root to each letter, writing 0 for each step left and 1 for each step right; the path is its code:

LetterCountCodeBits × count
A4501 × 45 = 45
C121003 × 12 = 36
B131013 × 13 = 39
F511004 × 5 = 20
E911014 × 9 = 36
D161113 × 16 = 48

224 bits in all, a quarter less than the fixed-length 300. That total is the weighted path length (WPL): each leaf's weight times its path length to the root, added up. The Huffman tree is the one with the smallest WPL.

All the letters are on leaves, so no code is the start of another (a prefix code). Decoding starts at the root and steps left or right bit by bit; reaching a leaf outputs a letter and goes back to the root, never ambiguous:

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

Decoding 1010100111: from the root, 0 goes left and 1 right; at a leaf, output it and go back to the root
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

Decode

Decode with this step's code table. It's a prefix code, so from the current position only one code can match: when one does, print its letter and skip past its length.

It should print
FABEC
exercise1.cpp
1#include <iostream>2#include <vector>3#include <string>4using namespace std;5 6int main() {7    vector<string> code = {"0", "101", "100", "111", "1101", "1100"};8    string letter = "ABCDEF";9    string bits = "110001011101100";10    size_t i = 0;11    while (i < bits.size()) {12        // try the 6 codes in turn: bits.compare(i, the code's length, code[k]) == 0 means it's this one13        break;14    }15    cout << "\n";16    return 0;17}
Output
Press Run or Ctrl+Enter

The WPL by hand

There's a simple trick: the WPL is the sum of the weights of the new nodes each merge makes (each merge a leaf goes into counts its weight once more, which counts it exactly its depth times). So the tree needn't even be built. The plain way first: each round, scan the vector for the two smallest.

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> w = {45, 13, 12, 16, 9, 5};7    int wpl = 0;8    while (w.size() > 1) {9        // find the two smallest: indexes x and y10        int x = 0, y = 1;11        if (w[y] < w[x]) { x = 1; y = 0; }12        for (int i = 2; i < (int)w.size(); i++)13            if (w[i] < w[x]) { y = x; x = i; }14            else if (w[i] < w[y]) y = i;15        int s = w[x] + w[y];16        cout << "merge " << w[x] << " and " << w[y] << " → " << s << "\n";17        wpl += s;18        // the new node goes at x, the last one moves to y, then the last slot goes19        w[x] = s;20        w[y] = w.back();21        w.pop_back();22    }23    cout << "WPL = " << wpl << "\n";24    return 0;25}
Output
merge 5 and 9 → 14
merge 12 and 13 → 25
merge 14 and 16 → 30
merge 25 and 30 → 55
merge 45 and 55 → 100
WPL = 224

One scan per round, O(n²) in all. With a few dozen letters that doesn't matter; the STL step swaps in a priority_queue for O(n log n).

Guess the outputA wrong guess is fine

The Huffman tree for weights 1, 2, 3, 4: what's its WPL?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> w = {1, 2, 3, 4};7    int wpl = 0;8    while (w.size() > 1) {9        int x = 0, y = 1;10        if (w[y] < w[x]) { x = 1; y = 0; }11        for (int i = 2; i < (int)w.size(); i++)12            if (w[i] < w[x]) { y = x; x = i; }13            else if (w[i] < w[y]) y = i;14        int s = w[x] + w[y];15        wpl += s;16        w[x] = s;17        w[y] = w.back();18        w.pop_back();19    }20    cout << wpl << "\n";21    return 0;22}

In exams: draw the Huffman tree for some weights, work out the WPL, write the codes. Some results that come up often: a Huffman tree with n leaves has 2n − 1 nodes in all (n − 1 merges); no node has just one child; one set of weights may give more than one tree (which goes left doesn't matter), but the WPL is always the same.

Choose one

Using a min-heap to find the two smallest, how long does building a Huffman tree for n letters take?

With the STL

For just the WPL, a min-heap of ints is enough:

main.cpp
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5using namespace std;6 7int main() {8    vector<int> w = {45, 13, 12, 16, 9, 5};9    priority_queue<int, vector<int>, greater<int>> q(w.begin(), w.end());  // O(n) heap building10    int wpl = 0;11    while (q.size() > 1) {12        int a = q.top(); q.pop();13        int b = q.top(); q.pop();14        wpl += a + b;15        q.push(a + b);16    }17    cout << "WPL = " << wpl << "\n";18    return 0;19}
Output
WPL = 224

For the code table, the tree has to be built for real. The heap holds Node*: leaves carry a letter, and each merge news a node whose left and right point at the two taken out. The comparator compares weights; for equal weights it compares the order they were made in, because otherwise, the heap not being stable, two runs (or another compiler) could put two equally heavy subtrees on different sides and the codes would change. Once the tree is built, one preorder walk gives the paths, which are the codes; last, a postorder walk deletes every node that was new'd.

main.cpp
1#include <iostream>2#include <vector>3#include <string>4#include <queue>5#include <map>6using namespace std;7 8struct Node {9    int w, id;         // weight, which one was made when10    char ch;           // a leaf's letter; merged nodes don't use it11    Node *left, *right;12    Node(int w, int id, char ch, Node* l, Node* r) : w(w), id(id), ch(ch), left(l), right(r) {}13};14 15void walk(Node* t, const string& path, map<char, string>& code) {16    if (!t->left) {                        // no Huffman node has just one child: no left child means a leaf17        code[t->ch] = path;18        return;19    }20    walk(t->left, path + "0", code);21    walk(t->right, path + "1", code);22}23 24void free_tree(Node* t) {25    if (!t) return;26    free_tree(t->left);27    free_tree(t->right);28    delete t;29}30 31int main() {32    string letters = "ABCDEF";33    vector<int> w = {45, 13, 12, 16, 9, 5};34    // "a comes out after b": the heavier later; equally heavy, the one made later35    auto later = [](Node* a, Node* b) {36        if (a->w != b->w) return a->w > b->w;37        return a->id > b->id;38    };39    priority_queue<Node*, vector<Node*>, decltype(later)> q(later);40    int id = 0;41    for (int i = 0; i < 6; i++)42        q.push(new Node(w[i], id++, letters[i], nullptr, nullptr));43    while (q.size() > 1) {44        Node* a = q.top(); q.pop();        // the smaller goes left45        Node* b = q.top(); q.pop();46        q.push(new Node(a->w + b->w, id++, 0, a, b));47    }48    Node* root = q.top();49 50    map<char, string> code;51    walk(root, "", code);52    int bits = 0;53    for (int i = 0; i < 6; i++) {54        cout << letters[i] << " " << code[letters[i]] << "\n";55        bits += w[i] * code[letters[i]].size();56    }57    cout << bits << " bits in all\n";58 59    string text = "BACD", out;60    for (char c : text) out += code[c];61    cout << text << " → " << out << "\n";62    free_tree(root);63    return 0;64}
Output
A 0
B 101
C 100
D 111
E 1101
F 1100
224 bits in all
BACD → 1010100111
StepWithTime
Build the heapa priority_queue built from a rangeO(n)
n − 1 mergestwo pops and one push eachO(n log n)
Make the code tableone preorder walk, into a map<char, string>O(n) nodes
Encode a textlook each character upO(log n) per character (map), O(1) with an array index

In interviews: Huffman itself is rare, but the shape "merge the two smallest" is common: "join n ropes, each join costs the two lengths together, find the least total cost" is the WPL, answered by the min-heap of ints above. With pointers in a priority_queue, the comparator must compare what they point at; comparing the pointers compares addresses.

Exercise 2

Work out the WPL

Weights 7, 5, 2, 4. Fill it in with a min-heap: each round take out the two smallest, merge them, add to wpl, and put the sum back.

It should print
35
exercise2.cpp
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5using namespace std;6 7int main() {8    vector<int> w = {7, 5, 2, 4};9    priority_queue<int, vector<int>, greater<int>> q(w.begin(), w.end());10    int wpl = 0;11    while (q.size() > 1) {12        // top + pop twice; add the sum to wpl; push the sum back13        break;14    }15    cout << wpl << "\n";16    return 0;17}
Output
Press Run or Ctrl+Enter
Choose one

The heap holds Node*, but the comparator is written [](Node* a, Node* b) { return a > b; }. What happens?

Guess the outputA wrong guess is fine

4 ropes, of length 4, 3, 2 and 6. Each time you join two ropes into one, it costs the sum of their lengths. Joining the two shortest each time, as the program does, what is the total cost?

1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5using namespace std;6 7int main() {8    vector<int> ropes = {4, 3, 2, 6};9    priority_queue<int, vector<int>, greater<int>> q(ropes.begin(), ropes.end());10    int cost = 0;11    while (q.size() > 1) {12        int a = q.top(); q.pop();13        int b = q.top(); q.pop();14        cost += a + b;15        q.push(a + b);16    }17    cout << cost << "\n";18    return 0;19}

Summary

Take-away

Huffman trees: merge the two smallest, again and again

  • Keep merging the two lightest trees; the new root weighs both; a min-heap makes it O(n log n)
  • 0 to the left, 1 to the right; all letters are on leaves, so it's a prefix code
  • WPL = Σ weight × depth = the sum of all merged nodes' weights, the smallest possible
  • n leaves make 2n − 1 nodes, and no node has just one child
1priority_queue<int, vector<int>, greater<int>> q(w.begin(), w.end());2while (q.size() > 1) {3    int a = q.top(); q.pop();4    int b = q.top(); q.pop();5    wpl += a + b; q.push(a + b);6}