HuffmanCode

Click here to download HKUAL_huffman_code.h Library

template < class T> class HuffmanCode;

Below is a sample program to use HuffmanCode

//Example usage of Humffman tree lib
#include <iostream>
#include <vector> #include "HKUAL_huffman_code.h" using namespace std; int main() { //a simple weight array int n = 9;
vector<double> weights; for(int i = 0; i < n; i++) { weights.push_back(i+1); } //build the Huffman encoding tree
vector<int> tree; double totalWeightedPathLength = HuffmanCode::BuildHuffmanTree(n, weights, tree); /* or double totalWeightedPathLength = HuffmanCode::TotalWeightedPathLength(n, weights); if there is no need to build the tree but only to calculate the cost */ cout << "Total weighted path length is " << totalWeightedPathLength << endl; //convert the encoding tree to 0-1 code
vector<string> code; HuffmanCode::HuffmanTreeToBinaryCode(n, tree, code); //output the code after encoding
for(int i=0; i<n; i++) {
cout << "[" << i << "] weight = " << weights[i] << " --> Code : " << code[i] << endl;
} return 0; }
© The University of Hong Kong Algorithms Library - hkual@cs.hku.hk