Kodewick
Start learning →
Huffman trees and Huffman codes26 / 50

Huffman trees and Huffman codes

Lesson 26 of 50 · Part 5 · Trees · about 15 minutes

A Huffman tree is built by merging the two smallest weights again and again; reading 0 for left and 1 for right gives a prefix code, where no code is the start of another, with the smallest total length, the weighted path length (WPL).

A text of 100 characters uses only 6 letters, A to F. Stored 3 bits each (000 to 101), that's 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 long and short so the total is smallest, and so that 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 repeat one thing: take the two trees with the smallest weights and merge them into one, the new root weighing the two together. When only 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: merging the two smallest each time builds the whole tree from the bottom up
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 left and 1 for right; the path is its code:

LetterTimesCodeBits × times
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 300 of fixed-length codes. This total is the weighted path length (WPL): each leaf's weight times its path length from the root, added up. The Huffman tree is the tree with the smallest WPL.

The letters are all at leaves, so no code is the start of another (a prefix code). Decoding starts at the root and goes left or right bit by bit; reaching a leaf, it outputs a letter and goes back to the root, never ambiguous: 1010100111 is 101, 0, 100, 111, which is B A C D.

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

Decoding 1010100: start at the root, 0 goes left and 1 goes right; at a leaf, output a letter 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 section's code table. Because it's a prefix code, only one code matches from the current position: when one matches, print its letter and skip past its length.

It should print
FABEC
exercise1.c
1#include <stdio.h>2#include <string.h>3 4const char *code[] = {"0", "101", "100", "111", "1101", "1100"};5const char letter[] = "ABCDEF";6 7int main(void) {8    const char *bits = "110001011101100";9    int i = 0, n = strlen(bits);10    while (i < n) {11        // try the 6 codes in turn: strncmp(bits + i, code[k], its length) == 0 means it's this one12        break;13    }14    printf("\n");15    return 0;16}
Output
Press Run or Ctrl+Enter

WPL in C

There is a simple way: the WPL equals the sum of the weights of the new nodes made by merging (each time a leaf is merged in, its weight is counted once more, exactly as many times as it is deep). So there's no need to even build the tree:

main.c
1#include <stdio.h>2 3int main(void) {4    int w[] = {45, 13, 12, 16, 9, 5};5    int n = 6, wpl = 0;6    while (n > 1) {7        // find the two smallest: indexes x and y8        int x = 0, y = 1;9        if (w[y] < w[x]) { x = 1; y = 0; }10        for (int i = 2; i < n; i++)11            if (w[i] < w[x]) { y = x; x = i; }12            else if (w[i] < w[y]) y = i;13        int s = w[x] + w[y];14        printf("merge %d and %d -> %d\n", w[x], w[y], s);15        wpl += s;16        // the new node takes x's place, the last one moves to y's17        w[x] = s;18        w[y] = w[n - 1];19        n--;20    }21    printf("WPL = %d\n", wpl);22    return 0;23}
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

Each round here scans for the two smallest, O(n²); a real implementation uses last lesson's min-heap, taking two and putting one back each round, O(n log n).

Guess the outputA wrong guess is fine

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

1#include <stdio.h>2 3int main(void) {4    int w[] = {1, 2, 3, 4};5    int n = 4, wpl = 0;6    while (n > 1) {7        int x = 0, y = 1;8        if (w[y] < w[x]) { x = 1; y = 0; }9        for (int i = 2; i < n; i++)10            if (w[i] < w[x]) { y = x; x = i; }11            else if (w[i] < w[y]) y = i;12        int s = w[x] + w[y];13        wpl += s;14        w[x] = s;15        w[y] = w[n - 1];16        n--;17    }18    printf("%d\n", wpl);19    return 0;20}

In exams: draw the Huffman tree for some weights, work out the WPL, write the codes. A few results asked often: a Huffman tree with n leaves has 2n − 1 nodes in all (n − 1 merges); no node has just one child; the same weights can draw more than one tree (which side is 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?

Exercise 2

Work out the WPL

Weights 7, 5, 2, 4. Finish it the way this section does: each round find the two smallest, merge them, add to wpl.

It should print
35
exercise2.c
1#include <stdio.h>2 3int main(void) {4    int w[] = {7, 5, 2, 4};5    int n = 4, wpl = 0;6    while (n > 1) {7        int x = 0, y = 1;8        if (w[y] < w[x]) { x = 1; y = 0; }9        for (int i = 2; i < n; i++)10            if (w[i] < w[x]) { y = x; x = i; }11            else if (w[i] < w[y]) y = i;12        // merge: s = the two added, into wpl; the new node goes to x, the last one moves to y, n goes down by 113        n--;14    }15    printf("%d\n", wpl);16    return 0;17}
Output
Press Run or Ctrl+Enter

Summary

Take-away

Huffman trees: merge the two smallest, again and again

  • Keep merging the two lightest trees; the new root weighs both together
  • 0 for left, 1 for right; the letters are all at leaves, so it's a prefix code
  • WPL = Σ weight × depth = the sum of every merged node's weight, the smallest possible
  • n leaves make 2n − 1 nodes, none with just one child
1while (n > 1) {2    take the smallest w[x], w[y];3    s = w[x] + w[y]; wpl += s;4    w[x] = s; w[y] = w[n - 1]; n--;5}