Huffman coding is an optimal algorithm for assigning variable-length binary codes to symbols based on their frequency. Common symbols receive shorter codes, while rare symbols receive longer codes, minimizing the total number of bits required for a message.
The Huffman Algorithm Process
- Initialize: Create a leaf node for each symbol with its frequency.
- Queue: Insert all nodes into a priority queue (min-heap) ordered by frequency.
- Iterate: While more than one node remains in the queue:
- Remove the two nodes with the lowest frequencies.
- Create a new internal node with these two as children.
- Set the new node's frequency to the sum of the children's frequencies.
- Insert the new node back into the queue.
- Root: The final remaining node is the root of the Huffman tree.
Prefix-Free Property
To ensure unambiguous decoding, Huffman codes must be prefix-free, meaning no code is a prefix of another. This is naturally guaranteed by the tree structure: symbols are only located at leaf nodes, and paths from the root to a leaf define the code (e.g., left=0, right=1).
/* Example Huffman Tree Structure */
(root)
/ \
0 1
/ \
[A] ( )
/ \
0 1
/ \
[B] ( )
/ \
0 1
/ \
[C] [D]
Codes:
A = 0
B = 10
C = 110
D = 111