TheAlgorithms/Go · error
huffman coding: HuffTree : calling method with empty list of
Error message
huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs
What it means
Raised by HuffTree when listfreq contains fewer than one SymbolFreq entry; building a Huffman tree requires at least one symbol, so an empty (or nil) slice cannot produce a root node. It is a generic input-size guard at the top of the method.
Source
Thrown at compression/huffmancoding.go:37
type Node struct {
left *Node
right *Node
symbol rune
weight int
}
// A SymbolFreq is a pair of a symbol and its associated frequency.
type SymbolFreq struct {
Symbol rune
Freq int
}
// HuffTree returns the root Node of the Huffman tree by compressing listfreq.
// The compression produces the most optimal code lengths, provided listfreq is ordered,
// i.e.: listfreq[i] <= listfreq[j], whenever i < j.
func HuffTree(listfreq []SymbolFreq) (*Node, error) {
if len(listfreq) < 1 {
return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs")
}
q1 := make([]Node, len(listfreq))
q2 := make([]Node, 0, len(listfreq))
for i, x := range listfreq { // after the loop, q1 is a slice of leaf nodes representing listfreq
q1[i] = Node{left: nil, right: nil, symbol: x.Symbol, weight: x.Freq}
}
//loop invariant: q1, q2 are ordered by increasing weights
for len(q1)+len(q2) > 1 {
var node1, node2 Node
node1, q1, q2 = least(q1, q2)
node2, q1, q2 = least(q1, q2)
node := Node{left: &node1, right: &node2,
symbol: -1, weight: node1.weight + node2.weight}
q2 = append(q2, node)
}
if len(q1) == 1 { // returns the remaining node in q1, q2
return &q1[0], nil
}View on GitHub (pinned to 5ba447ec5f)
Solutions
- Pass a non-empty []SymbolFreq slice to HuffTree
- Check len(listfreq) > 0 before calling and construct a trivial single-node tree for one symbol
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at compression/huffmancoding.go:37 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/acfc266fb8afc84d.
Report an issue: GitHub.