哈弗曼树的建立和应用

  • 格式:doc
  • 大小:48.00 KB
  • 文档页数:4

哈弗曼树的建立和应用
#include<iostream>
#include<iomanip>
using namespace std;
const int n=8; //表示叶子数目
const int m=2*n-1; //森林中数的棵数struct tree //哈夫曼树中的一个结点{
float weight; //权值
int parent; //双亲
int lc,rc; //左右孩子
};
struct codetype //哈弗曼编码
{
int bits[n+1]; //编码的存放位置
int star; //开始存放位置
char c; //对应的字符
};
tree hftree[m+1];
codetype code[n+1];
void create_hftree() //建立哈夫曼树
{
int i,j,p1,p2;
float s1,s2;
for(i=1;i<=m;i++)
{
hftree[i].parent=0;
hftree[i].lc=0;
hftree[i].rc;
hftree[i].weight=0;
}
cout<<"请输入"<<n<<"个权值"<<endl;
for(i=1;i<=n;i++)
cin>>hftree[i].weight;
for(i=n+1;i<=m;i++)
{
p1=p2=0;
s1=s2=31767;
for(j=1;j<i-1;j++)
if(hftree[j].parent==0)
if(hftree[j].weight<s1)
{
s2=s1;
s1=hftree[j].weight;
p2=p1;
p1=j;
}
else
if(hftree[j].weight<s2)
{
s2=hftree[j].weight;
p2=j;
}
hftree[p1].parent=i;
hftree[p2].parent=i;
hftree[i].lc=p1;
hftree[i].rc=p2;
hftree[i].weight=hftree[p1].weight=hftree[p1].weight+hftree[p2].weight;
}
}
void huffcode()
{
codetype cd;
int c,p;
for(int i=1;i<=n;i++)
{
cd.star=n+1;
cd.c=96+i; //第一个树叶对应的字母a,其余依次类推
c=i;
p=hftree[i].parent;
while(p!=0)
{
cd.star--;
if(hftree[p].lc==c) cd.bits[cd.star]=0;
else cd.bits[cd.star]=1;
c=p;
p=hftree[p].parent;
}
code[i]=cd;
}
for(int j=1;j<=n;j++)
{
cout<<"字符"<<code[j].c<<"的权值为:"<<hftree[j].weight<<setw(5)<<"编码为:";
for(int k=code[j].star;k<=n;k++)
cout<<code[j].bits[k]<<" ";
cout<<endl;
}
}
void trancode()
{
int i=m;
char b;
cout<<"请输入一串2进制的编码(0、1以外的数结束)";
cin>>b;
while((b=='0')||(b=='1'))
{
if(b=='0') i=hftree[i].lc;
else i=hftree[i].rc;
if(hftree[i].lc==0)
{
cout<<code[i].c;
i=m;
}
cin>>b;
}
}
void main()
{
create_hftree(); //建立哈弗曼树
huffcode(); //实现哈弗曼编码
trancode(); //实现哈弗曼译码
}。