哈夫曼树还是比较实用的,又简单。
具体的实现方法:设一个优先级队列,频率越小的字母越优先。
每次都从队列中取出最前面两个元素,合并成一个新的元素。
直到元素只剩一个。
具体的实现细节看代码吧。
#include<iostream>
#include<vector>
#include<string>
#include<queue>
using namespace std;
typedef struct node
{
char m;
int v;
node *left,*right;
}node;
typedef struct comp
{
bool operator () (node *a,node *b)
{
return a->v>b->v;
}
}comp;
void outcode(node* T,string &s)//输出编码 用引用节约空间
{
if(T->left!=NULL)
{
s.push_back('0');
outcode(T->left,s);
s.pop_back();
}
if(T->right!=NULL)
{
s.push_back('1');
outcode(T->right,s);
s.pop_back();
}
if(T->left==NULL&&T->right==NULL)
{
cout<<T->m<<" "<<s<<endl;
}
}
int ma