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.
(listfreq []SymbolFreq)
| 33 | // The compression produces the most optimal code lengths, provided listfreq is ordered, |
| 34 | // i.e.: listfreq[i] <= listfreq[j], whenever i < j. |
| 35 | func HuffTree(listfreq []SymbolFreq) (*Node, error) { |
| 36 | if len(listfreq) < 1 { |
| 37 | return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs") |
| 38 | } |
| 39 | q1 := make([]Node, len(listfreq)) |
| 40 | q2 := make([]Node, 0, len(listfreq)) |
| 41 | for i, x := range listfreq { // after the loop, q1 is a slice of leaf nodes representing listfreq |
| 42 | q1[i] = Node{left: nil, right: nil, symbol: x.Symbol, weight: x.Freq} |
| 43 | } |
| 44 | //loop invariant: q1, q2 are ordered by increasing weights |
| 45 | for len(q1)+len(q2) > 1 { |
| 46 | var node1, node2 Node |
| 47 | node1, q1, q2 = least(q1, q2) |
| 48 | node2, q1, q2 = least(q1, q2) |
| 49 | node := Node{left: &node1, right: &node2, |
| 50 | symbol: -1, weight: node1.weight + node2.weight} |
| 51 | q2 = append(q2, node) |
| 52 | } |
| 53 | if len(q1) == 1 { // returns the remaining node in q1, q2 |
| 54 | return &q1[0], nil |
| 55 | } |
| 56 | return &q2[0], nil |
| 57 | } |
| 58 | |
| 59 | // least removes the node with lowest weight from q1, q2. |
| 60 | // It returns the node with lowest weight and the slices q1, q2 after the update. |