AQA GCSE Computer Science (8525), section 3.3.8 (Data compression)
The idea
In ordinary ASCII every character uses the same number of bits. In Huffman coding, characters that occur most often get shorter codes, and rare ones get longer codes. The text then needs fewer bits overall. It is lossless.
Huffman tree
The codes come from a binary tree. The characters are at the ends (leaves). To find the code for a character, follow the branches from the top, writing 0 for a left branch and 1 for a right branch (as labelled in the tree).
Each leaf is labelled with its character and frequency (how often it occurs).
Building a tree
For the message with frequencies A = 8, B = 4, C = 2, D = 1 (15 characters):
- List the characters in order of frequency.
- Join the two lowest frequencies: D (1) and C (2) make a node of 3.
- Join the next two lowest: that node (3) and B (4) make 7.
- Join the last two: 7 and A (8) make 15, the top of the tree.
The codes
| Character | Code | Bits |
|---|---|---|
| A | 0 | 1 |
| B | 10 | 2 |
| C | 110 | 3 |
| D | 111 | 3 |
The most common letter, A, has the shortest code.
Bits needed
Number of bits with Huffman coding = sum of (frequency × code length):
With ASCII (8 bits for each of 15 characters): bits.
Bits saved = bits.
(Check whether the question tells you to use 7 or 8 bits for each ASCII character. Many questions use 8 bits, one byte, per character.)
Decoding
Read the bits from the left, following the tree until you reach a leaf, write the character, then start again from the top.
0 10 110 0 is A B C A.
Huffman codes work because no code is the start of another code, so there is no confusion about where one character ends.
Common mistake: giving every character the same length code. Huffman codes are different lengths, and the most frequent character has the shortest. Also, when reading a code from the tree, always start at the top, and do not mix up the 0 and 1 branches.
Exam tip: to calculate bits saved: work out the Huffman total (frequency × code length, added up), the ASCII total (characters × bits each), then subtract. Show each step.
Check yourself
In Huffman coding, which characters get the shortest codes?
The characters that occur most frequently.
Using the codes A = 0, B = 10, C = 110, D = 111, decode 110 0 10.
C A B.
Why does Huffman coding reduce the number of bits needed?
Common characters use fewer bits than the fixed size normally used, so the total is smaller.