Sub topic 4
Representing Codes as Binary Trees
This chapter assumes you know binary trees and recursive traversal, can read Python dictionaries and generators, and have met prefix-free codes from the previous chapter. Here you will turn a code table into a tree. That tree is the structure Huffman's algorithm builds and the decoder walks.
The Mapping Between Codes and Paths
Any set of binary codewords can be drawn as a binary tree:
- Start at the root.
- Each
0bit moves to the left child and each1bit moves to the right child. - The node where a codeword ends holds that symbol.
The bits of a codeword are the path from the root to its symbol. A codeword's length is the depth of its node.
Here is the code a = 0, b = 10, c = 110, d = 111 drawn as a tree:
Prefix-Free Means Symbols Sit Only at Leaves
A code is prefix-free when no codeword is the start of another codeword. In the tree, this means every symbol sits at a leaf. Suppose a = 0 and b = 01. Then a sits on the path to b, so the node for a would need to be a symbol and an internal node at once. Reading 0, the decoder cannot tell whether to stop at a or keep going toward b.
So you can check whether a code is prefix-free by building its tree. If a codeword ends at an internal node, or a path runs through a node that already holds a symbol, the code is not prefix-free.
def build_tree(codes):
root = {}
for sym, code in codes.items():
node = root
for bit in code:
if "sym" in node:
raise ValueError(f"code of {node['sym']!r} is a prefix of code of {sym!r}")
node = node.setdefault(bit, {})
if node:
raise ValueError(f"code of {sym!r} is a prefix of (or equal to) another code")
node["sym"] = sym
return root
def leaves(node, prefix=""):
if "sym" in node:
yield node["sym"], prefix
return
for bit in "01":
if bit in node:
yield from leaves(node[bit], prefix + bit)
def is_full(node):
if "sym" in node:
return True
return ("0" in node and "1" in node
and is_full(node["0"]) and is_full(node["1"]))
good = build_tree({"a": "0", "b": "10", "c": "110", "d": "111"})
print(list(leaves(good))) # [('a', '0'), ('b', '10'), ('c', '110'), ('d', '111')]
print(is_full(good)) # True
print(is_full(build_tree({"a": "00", "b": "01", "c": "11"}))) # False
try:
build_tree({"a": "0", "b": "01"})
except ValueError as e:
print(e) # code of 'a' is a prefix of code of 'b'Full Trees: No Wasted Branches
A tree is full when every internal node has exactly two children. The code a = 00, b = 01, c = 11 is prefix-free, but its tree is not full. The node reached by 1 has only one child, so c could be shortened to 1 and the code would still be prefix-free. An optimal code never has a one-child node. This is why Huffman's algorithm always merges exactly two nodes at a time, which produces a full tree.
Cost of a Tree
If symbol s appears f(s) times and sits at depth d(s), the encoded message takes Σ f(s)·d(s) bits. This sum is the tree's weighted path length. To compress well, you want a tree that keeps this sum small, with frequent symbols near the root and rare ones deep. The next chapter shows how Huffman's algorithm builds such a tree.
| Symbol | Frequency | Depth | Bits contributed |
|---|---|---|---|
| a | 5 | 1 | 5 |
| b | 2 | 2 | 4 |
| c | 1 | 3 | 3 |
| d | 1 | 3 | 3 |
With these counts the message takes 15 bits in total. A 2-bit fixed-length code would take 18 bits.
Exercise
Is the code {x: 1, y: 01, z: 001} prefix-free? Is its tree full? If it is not full, give a shorter prefix-free code for the same three symbols.
Show answer
It is prefix-free because every symbol ends at a leaf. The tree is not full: the node reached by 00 has only a 1 child. Moving z up gives {x: 1, y: 01, z: 00}, which is prefix-free and full.
Exercise
Using the table above, what happens to the total bit count if you swap the codes of a and d?
Show answer
a moves to depth 3 and d moves to depth 1. The total becomes 5·3 + 2·2 + 1·3 + 1·1 = 23 bits, up from 15, because the most frequent symbol now has the longest path.