The text changed. Select Build example to update the lesson below.
Available nodes · smallest first
The tree grows here
Each leaf shows a symbol and its frequency.
Your worked example
Follow the edges from the root to a symbol. The 0s and 1s form its code. Select a symbol to highlight that path.
| Symbol | Frequency | Code | Length | f × length |
|---|---|---|---|---|
| Total encoded bits | ||||
Add frequency × code length:
These are payload bits. A real compressed file also needs its tree/codebook and framing. Short messages may take more total space once that information is included.
The codes are prefix-free: no complete code is the beginning of another complete code. This lets the receiver separate the symbols.
Encode your text
Replace each symbol with its code, keeping the original order.
See how the same tree decodes the bits
Start at the root. Read 0 to go left or 1 to go right. At a leaf, write its symbol and start again at the root.
Recovered text
Methodology
- Count each symbol’s frequency.
- Sort the available nodes from smallest to largest.
- Take the two smallest nodes. Their sum becomes a new parent.
- Put that parent back into the sorted list. Repeat until one root remains.
- Assign 0 to left edges and 1 to right edges. Read each symbol’s code from the root.
Equal frequencies: this app chooses the node created earlier. Original symbols are created in the order they first appear; new parents are created later. The first selected node goes left (0), the second goes right (1). Other consistent tie choices can give different valid codes with the same minimum total bit cost.
One different symbol: there is nothing to merge. This lesson assigns code 0 to each occurrence.
Text is kept exactly: uppercase and lowercase differ; spaces, tabs and line breaks count. A symbol here means one Unicode code point, so some accented characters and joined emoji use more than one symbol.
Lossless: decoding the generated bits with the same tree reproduces the original text. Huffman coding minimizes the weighted code length among binary prefix codes for the supplied symbol frequencies.