构造哈夫曼树生成哈夫曼编码
参考
程序员小灰-漫画:什么是 “哈夫曼树” ?
程序员小灰-漫画:“哈夫曼编码” 是什么鬼?
编写一个程序exp7-5.cpp,构造一棵哈夫曼树,
输出对应的哈夫曼编码和平均查找长度,
并对下表(表7.8)所示的数据进行验证。
表7.8 单词及出现的频度
单词 The of a to and in that he is at on for His are be
频度 1192 677 541 518 462 450 242 195 190 181 174 157 138 124 123
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct TreeNode{
int weight=0;
string word;
string huffmancode;
struct TreeNode* lChild;
struct TreeNode* rChild;
};
TreeNode *w_node[15];
class cmp{
public:
bool operator()(const TreeNode *n1,const TreeNode *n2)const{
return n1->weight > n2->weight;
}
};
//创建哈夫曼树
TreeNode* CreateHuffmanTree(int w[],string s[]){
priority_queue<TreeNode*,vector<TreeNode*>,cmp > q;
for(int i = 0;i < 15; i++){
TreeNode* node = new TreeNode;
node->lChild = node->rChild = NULL;
node->weight = w[i];
node->word = s[i];
q.push(node);
w_node[i] = node; //记录下原本的点
}
while (q.size()>1)
{
TreeNode *parent = new TreeNode;
parent->lChild = q.top();
q.pop();
parent->rChild = q.top();
q.pop();
parent->weight = parent->lChild->weight + parent->rChild->weight;
q.push(parent);
}
return q.top();
}
//递归编码
void encode(TreeNode *node,string code){
if(node==NULL)return;
node->huffmancode = code;
encode(node->lChild,code+'0');
encode(node->rChild,code+'1');
}
//WPL
int getWPL(TreeNode *node,int depth){
if(node->lChild==NULL&&node->rChild==NULL){
return node->weight*depth;
}
return getWPL(node->lChild,depth+1)+getWPL(node->rChild,depth+1);
}
int main(){
int weight[] = {1192,677,541,518,462,450,242,195,190,181,174,157,138,124,123};
string s[] = {"The","of","a","to","and","in","that","he","is","at","on","for","His","are","be"};
TreeNode *root = CreateHuffmanTree(weight,s);
encode(root,"");
for(int i=0;i<15;i++){
cout<<w_node[i]->word<<":"<<w_node[i]->huffmancode<<endl;
}
cout<<"平均查找长度:"<<getWPL(root,0);
system("pause");
return 0;
}