Huffman Coding Tree Visualizer — Free Interactive Compression Demo

Huffman Coding Tree Visualizer · Visualizers · Plain HTML, CSS & JS · Live preview

CategoryVisualizers

What's included

Features

Step-by-step merging
Two lightest trees combined per step.
Whole forest drawn
Every subtree visible between merges.
Edge bits labelled
0 for left, 1 for right.
Prefix-free code table
Character, count, code and bits used.
Size comparison
Huffman vs fixed-length vs 8-bit ASCII.
Encoded bit stream
Per-character codes shown in sequence.
Deterministic ties
Stable ordering by creation.
No libraries
SVG layout computed in plain JS.

About this UI Snippet

Huffman Coding — Building an Optimal Prefix Code by Hand

Screenshot of the Huffman Coding Tree Visualizer snippet rendered live

Huffman coding is how lossless compression gives common symbols short codes and rare symbols long ones. It's inside DEFLATE (ZIP, gzip, PNG), JPEG and MP3. The algorithm is surprisingly small — a loop that merges the two lightest trees — and this visualizer lets you run that loop yourself on your own text.

Start with a forest

Count how often each character appears. Each distinct character becomes its own one-node tree, weighted by its count.

Merge the two lightest, repeatedly

Take the two trees with the smallest weights, make them the left and right children of a new node whose weight is their sum, and put that node back in the forest. Each merge reduces the number of trees by one, so a text with k distinct characters needs k − 1 merges. The newest node is highlighted in amber so you can follow each step.

Reading the codes

In the finished tree, every left edge means 0 and every right edge means 1. A character's code is the path from the root to its leaf. Because characters only live at leaves, no code can be the start of another code — the "prefix-free" property that lets a decoder read the bit stream without separators.

Why it's optimal

The two rarest symbols end up deepest, so they get the longest codes, and every merge pushes the least frequent weight down the tree. Huffman proved this gives the shortest possible average code length for a code that assigns whole bits to each symbol.

Measuring the saving

The summary compares the Huffman-encoded length with a fixed-length code (just enough bits for the number of distinct characters) and with 8-bit ASCII, and shows the actual bit stream split per character. A real compressed file also has to store the tree or code table, which matters for short inputs like these.

Deterministic ties

When two trees have equal weight, the one created earlier is taken first. Different tie-breaks give different, equally optimal codes.

Build with AI

Build, Understand, Optimize, and Extend It With AI

Paste this visualizer into an AI assistant like Claude and ask it to explain why merging the two lightest trees is always safe — the greedy-choice argument. Ask it to add a decoder that walks the tree bit by bit as you click, canonical Huffman codes like DEFLATE uses, an entropy calculation for comparison, or a binary heap instead of sorting. It can also estimate how much the stored code table costs for short inputs.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build an interactive Huffman coding visualizer in plain HTML, CSS and JavaScript.

Requirements:
- A text input (up to 40 characters) and Start button that counts character frequencies and creates one single-node tree per distinct character, sorted by weight with a stable tie-break by creation order.
- A "Merge two smallest" button that removes the two lightest trees, creates a parent with their combined weight, re-inserts it and highlights the new node, plus a "Build whole tree" button.
- Draw the entire forest in SVG after every step, positioning leaves in consecutive slots, parents midway between their children and rows by depth, with edges labelled 0 (left) and 1 (right).
- When one tree remains, derive each character's code from its root-to-leaf path and show a table of character, count, code and total bits.
- Show the total encoded length compared with a fixed-length code and 8-bit ASCII, the average bits per character, and the encoded bit stream split per character.
- Display spaces with a visible symbol.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.

Source Code

<div class="hf">
  <div class="hf-top">
    <div>
      <h2>Huffman coding</h2>
      <p>Frequent letters get short codes, rare letters get long ones — and no code is a prefix of another.</p>
    </div>
    <form class="hf-form" id="hfForm">
      <input id="hfText" value="mississippi river" maxlength="40" aria-label="Text to encode" autocomplete="off">
      <button type="submit">Start</button>
    </form>
  </div>
  <div class="hf-ctrl">
    <button type="button" id="hfStep">Merge two smallest</button>
    <button type="button" id="hfAll" class="ghost">Build whole tree</button>
    <span id="hfMsg" aria-live="polite"></span>
  </div>
  <svg id="hfSvg" viewBox="0 0 900 330" role="img" aria-label="Huffman forest"></svg>
  <div class="hf-out">
    <table class="hf-table"><thead><tr><th>Char</th><th>Count</th><th>Code</th><th>Bits</th></tr></thead><tbody id="hfCodes"></tbody></table>
    <div class="hf-bits">
      <div class="hf-sum" id="hfSum"></div>
      <div class="hf-stream" id="hfStream"></div>
    </div>
  </div>
</div>

Step by step

How to Use

  1. 1
    Enter textUp to 40 characters, then press Start.
  2. 2
    Merge step by stepEach click joins the two lightest trees; the new node is highlighted.
  3. 3
    Or build it allBuild whole tree runs every merge.
  4. 4
    Read the codesLeft edges are 0, right edges are 1.
  5. 5
    Compare sizesSee Huffman bits vs fixed-length vs ASCII.

Real-world uses

Common Use Cases

Algorithms courses
Greedy algorithms and optimal codes.
Understanding compression
What ZIP and PNG do under the hood.
Interview preparation
A classic priority-queue problem.
Information theory intros
Relate code length to frequency.
Teaching
Build a tree for a student's own name.
Related: Binary Heap Priority Queue
The structure used to find the two lightest trees: Binary Heap Priority Queue Visualizer.
Related: Big-O Growth Visualizer
Why efficient structures matter: Big-O Complexity Growth Visualizer.

Got questions?

Frequently Asked Questions

Count symbol frequencies, make one weighted tree per symbol, then repeatedly merge the two lightest trees under a new node whose weight is their sum until one tree remains. Codes are the paths from the root to each leaf, using 0 for left and 1 for right.

No code is the beginning of another code. Because symbols are only at leaves, a decoder can read bits one at a time, walk the tree, and output a symbol whenever it reaches a leaf, with no separators needed.

It produces the shortest possible average code length among codes that use a whole number of bits per symbol. Arithmetic coding and ANS can get closer to the theoretical entropy limit by using fractional bits.

When weights tie, either tree can be merged first, and left/right can be swapped. All such choices produce codes with the same total length, but the individual codes differ.

In DEFLATE (used by ZIP, gzip and PNG), in JPEG and in MP3, usually combined with other techniques like LZ77 or transforms that make the data more compressible first.