Watch Huffman coding merge the two rarest letters again and again into a tree, then read off each prefix code. Worked example with a 5, b 2, c 1 and d 3.
About this algorithm
Huffman coding gives each character a binary code whose length depends on how often it appears: common characters get short codes, rare ones get long codes. It builds the codes from a binary tree, made by repeatedly joining the two least frequent nodes. No code is the start of another, so a stream of bits can be decoded without separators.
Use Huffman coding for lossless compression when some symbols are much more common than others, which is true of text, pixel values and audio samples. It is one stage of DEFLATE (the format behind zip, gzip and PNG) and of JPEG and MP3. A fixed-length code, such as 8 bits per character, is simpler and wins when every symbol is about equally likely. Arithmetic coding can get closer to the theoretical limit when probabilities are very skewed, at the cost of more complex code. Among the greedy pages, this is the one that builds a structure instead of picking from a list.
Each leaf holds a character and how many times it appears. Put all leaves in a min-priority queue keyed by that count.
Remove the two nodes with the lowest counts. Make a new parent node whose count is their sum, with the first one as its left child and the second as its right child. Put the parent back in the queue.
Each join removes two nodes and adds one, so k characters need k - 1 joins. The last node is the root of the tree.
Walk from the root to every leaf, writing 0 for each step left and 1 for each step right. The path to a leaf is that character's code.
The page loads four characters with counts a 5, b 2, c 1 and d 3, eleven characters in all. The queue in order is c 1, b 2, d 3, a 5. Join c and b into a node of 3. Now d and the new node both have 3; d was in the queue first, so it becomes the left child of a node of 6. Finally a (5) and that node (6) join into the root, 11. Reading the paths gives a = 0, d = 10, c = 110 and b = 111. The encoded text takes 5 × 1 + 3 × 2 + 1 × 3 + 2 × 3 = 20 bits, against 22 bits with a fixed 2-bit code for four letters. To decode 010110, read bits until they match a code: 0 is a, 10 is d, 110 is c.
When two nodes have the same count, either can go first. A different choice can give different codes, but the total number of bits comes out the same, and every such tree is optimal. The decoder must use the same tree as the encoder, which is why compressed files store the code table or the counts.
Time: there are k - 1 joins, each doing two removals and one insert on a binary heap of at most k nodes, at log k each; this page keeps its queue as a re-sorted list to draw it, which is slower but gives the same tree. Space: the tree has k leaves and k - 1 inner nodes, and the code table has one entry per character.