Why give ‘e’ and ‘z’ the same number of bits when one is everywhere and the other is rare? Huffman’s greedy trick builds the shortest possible prefix code: merge the two rarest symbols, repeat, and the tree that falls out is provably optimal. Slide through the symbols and read each one’s codeword off the branches.
Build a forest of leaves weighted by frequency; repeatedly merge the two lowest-weight trees; the path from root (0=left,1=right) spells each symbol’s code. Because rarer symbols sink deeper, the frequency-weighted average length is minimised, and no code is a prefix of another so the stream self-delimits. A fail-loud self-check throws unless the codes are prefix-free AND the average length sits between Shannon’s entropy H and H+1 bits — the optimality window Huffman (1952) guarantees.
One frequency table is shown; Huffman is optimal among symbol codes, but arithmetic/range coders can beat it toward the entropy limit for skewed sources. The prefix-free property and the H ≤ avg < H+1 bound are exact here.