Skip to content
ufraan
← Back

Huffman

Huffman coding in C++ - builds the tree from character frequencies, encodes text to variable-length codes and decodes it back.

C++Algorithms
Sep 2026GitHub

A single-file Huffman coding implementation in C++. It counts character frequencies, builds the Huffman tree with a priority queue, walks the tree to assign a variable-length binary code to each character, and then decodes the bitstring back into the original text.

pownload landing page with marquee strips of screenshots
pownload landing page with marquee strips of screenshots

Frequent characters end up with short codes and rare ones with long codes, which is the entire point of the algorithm - the encoded output is smaller than fixed-width ASCII for most text. Decoding is the mirror image of encoding: start at the root, walk left on a zero and right on a one, and whenever you land on a leaf, emit that character and jump back to the root.

It also packs the raw bitstream into real bytes before printing it, so you can see how many bytes the text actually costs rather than counting bits by hand.

Written as one main.cpp with the reasoning left in the comments, as a way to work through the algorithm properly.