Sub topic 4
Representing Codes as Binary Trees
This chapter assumes you can read Python, know what a binary tree is, and can follow a recursive traversal. It also builds on the previous chapter's idea of a prefix-free code, which is a set of codewords where no codeword is the start of another. Here you will learn to see a code as a tree. The Huffman algorithm, the encoder, and the decoder all work on that tree, so the rest of the tutorial depends on this view.
The mapping between codes and trees
A binary code tree is a binary tree whose edges carry bit labels. By convention the edge to the left child is labeled 0 and the edge to the right child is labeled 1. Each symbol sits at a node. The symbol's codeword is the sequence of edge labels on the path from the root to that node.
Take this code for the symbols in abracadabra:
| Symbol | Frequency | Codeword | Depth |
|---|---|---|---|
| a | 5 | 0 | 1 |
| b | 2 | 10 | 2 |
| r | 2 | 110 | 3 |
| c | 1 | 1110 | 4 |
| d | 1 | 1111 | 4 |
Reading 110 as a path means: go right, go right, go left, and you reach r.
These tree properties carry over directly to properties of the code:
| Tree property | Code property |
|---|---|
| Depth of a symbol's node | Length of its codeword in bits |
| Symbols only at leaves | Code is prefix-free |
| Every internal node has two children (a full tree) | No codeword can be shortened without breaking prefix-freeness |
| Sum of frequency × depth over leaves | Total encoded size in bits |
| Number of leaves | Alphabet size |
Why leaves mean prefix-free
Suppose codeword X is a prefix of codeword Y. Then the path for X is the first part of the path for Y, so X's node is an ancestor of Y's node. That means X's node is internal, not a leaf. The reverse also holds. If a symbol sits at an internal node, then every symbol below it has a codeword that starts with that symbol's codeword.
So a code is prefix-free exactly when every symbol is on a leaf. This test is easy to check mechanically. It is also why decoding works: you walk down from the root bit by bit, and when you land on a leaf, the symbol is fully determined because nothing continues below it.
Building a tree from a code table, with validation
The code below turns a codeword table into a tree. It rejects duplicate codewords, empty codewords, and prefix violations. The violations get caught in both directions: a short codeword inserted before a longer one, or after it.
from fractions import Fraction
class Node:
def __init__(self):
self.children = {} # maps "0" or "1" to a child Node
self.symbol = None # set only on leaves
def tree_from_codes(codes):
root = Node()
for sym, code in codes.items():
if code == "" or set(code) - {"0", "1"}:
raise ValueError(f"invalid codeword {code!r} for {sym!r}")
node = root
for bit in code:
if node.symbol is not None:
raise ValueError(f"code of {node.symbol!r} is a prefix of code of {sym!r}")
node = node.children.setdefault(bit, Node())
if node.symbol is not None:
raise ValueError(f"{sym!r} and {node.symbol!r} share codeword {code}")
if node.children:
raise ValueError(f"code of {sym!r} is a prefix of another codeword")
node.symbol = sym
return root
def is_full(node):
if node.symbol is not None:
return True
return len(node.children) == 2 and all(is_full(c) for c in node.children.values())
def leaves(node, prefix=""):
if node.symbol is not None:
yield node.symbol, prefix
for bit in sorted(node.children):
yield from leaves(node.children[bit], prefix + bit)
def kraft_sum(codes):
return sum(Fraction(1, 2 ** len(c)) for c in codes.values())
good = {"a": "0", "b": "10", "r": "110", "c": "1110", "d": "1111"}
root = tree_from_codes(good)
print(list(leaves(root)))
print("full:", is_full(root), "kraft:", kraft_sum(good))
wasteful = {"a": "0", "b": "10", "c": "110"}
print("full:", is_full(tree_from_codes(wasteful)), "kraft:", kraft_sum(wasteful))
try:
tree_from_codes({"a": "1", "b": "10"})
except ValueError as e:
print("rejected:", e)Running it prints:
[('a', '0'), ('b', '10'), ('r', '110'), ('c', '1110'), ('d', '1111')]
full: True kraft: 1
full: False kraft: 7/8
rejected: code of 'a' is a prefix of code of 'b'Full trees and wasted bits
The wasteful code is prefix-free but not efficient. In its tree, the node at path 11 has only one child, 110. Since nothing else hangs under 11, you can move c up to 11 and the code stays prefix-free. Every c then costs one bit less. More generally, any internal node with a single child can be removed by pulling its subtree up one level. That shortens every codeword below it.
An optimal prefix code therefore always has a full tree, meaning every internal node has exactly two children. Huffman's algorithm produces full trees by construction, because every merge joins exactly two nodes. If a code you inherit from somewhere fails is_full, it is leaving bits on the table.
The Kraft inequality
The kraft_sum function computes the sum of 2^(−length) over all codewords. Picture each codeword of length l as claiming a 2^(−l) share of the tree: a depth-1 leaf takes half the space, a depth-2 leaf a quarter, and so on. Leaves of a prefix code never overlap, so their shares cannot add up to more than 1. This gives the Kraft inequality:
- If the codeword lengths l₁, …, lₙ belong to a prefix code, then the sum of 2^(−lᵢ) is at most 1.
- Conversely, if a set of lengths satisfies the inequality, some prefix code with those lengths exists.
- The sum equals exactly 1 when the tree is full. The
wastefulcode's 7/8 means one-eighth of the tree is unused.
The converse matters later. It says the lengths alone determine whether a valid code exists. The specific bit patterns are a free choice. The canonical Huffman chapter uses that freedom to rebuild a code from its lengths alone.
Cost as weighted depth
With frequencies f(s) and depths d(s), the encoded size of a message is the sum of f(s)·d(s) over all symbols. For the table above:
5·1 + 2·2 + 2·3 + 1·4 + 1·4 = 23 bits
A fixed 3-bit code for five symbols would need 11·3 = 33 bits. If you divide by the message length, you get the expected codeword length, the sum of p(s)·d(s), which here is 23/11 ≈ 2.09 bits per symbol. Finding the best code is the same as finding the full binary tree with the given leaves that has the smallest weighted depth. Huffman's algorithm solves that problem, and the next chapter covers how.
def weighted_depth(root, freq):
return sum(freq[sym] * len(code) for sym, code in leaves(root))
freq = {"a": 5, "b": 2, "r": 2, "c": 1, "d": 1}
print(weighted_depth(tree_from_codes(good), freq)) # 23Lighter representations
The Node class is explicit, but nested tuples work just as well. A leaf is the symbol itself, and an internal node is a pair (left, right). The tree above becomes:
tree = ("a", ("b", ("r", ("c", "d"))))
def codes_from_tuple(node, prefix=""):
if isinstance(node, tuple):
yield from codes_from_tuple(node[0], prefix + "0")
yield from codes_from_tuple(node[1], prefix + "1")
else:
yield node, prefix
print(dict(codes_from_tuple(tree)))
# {'a': '0', 'b': '10', 'r': '110', 'c': '1110', 'd': '1111'}The Huffman builder in the next chapter uses this form. Notice that a tuple is always a pair, so this representation can only express full trees. One catch: symbols must not themselves be tuples, or the isinstance check will misread them as internal nodes. Characters and integers are safe.
Common errors
- Placing a symbol on an internal node, for example when writing codes by hand. Validate with a tree build like
tree_from_codes. - Treating left as
1in one place and0in another. The convention is arbitrary, but encoder and decoder must agree. - Assuming a prefix-free code is efficient. Check that the tree is full, which is the same as the Kraft sum equaling 1.
- Counting depth from 1 at the root. The root has depth 0, and depth equals codeword length.
Exercise
Is the code {w: 00, x: 01, y: 10, z: 110} prefix-free? Is its tree full? What is its Kraft sum, and how would you improve it?
Show answer
It is prefix-free, because all four symbols are leaves. The tree is not full: the node at path 11 has only the child 110. The Kraft sum is 1/4 + 1/4 + 1/4 + 1/8 = 7/8. Moving z up to 11 gives {w: 00, x: 01, y: 10, z: 11}, which has a Kraft sum of 1 and saves one bit per z.
Exercise
Can a prefix code have codeword lengths 1, 2, 2, 3? Use the Kraft inequality.
Show answer
No. The sum 1/2 + 1/4 + 1/4 + 1/8 = 9/8 is greater than 1, so no prefix code has these lengths. Once the depth-1 and two depth-2 leaves are placed, the tree has no room left.
Exercise
With frequencies a: 5, b: 2, r: 2, c: 1, d: 1, compute the total bits for the tree ("a", (("b", "r"), ("c", "d"))) and compare it with the 23-bit tree in this chapter.
Show answer
The depths are a = 1 and b, r, c, d = 3. The total is 5·1 + (2 + 2 + 1 + 1)·3 = 23 bits. Both trees cost the same, which shows that different trees can be equally optimal.