构造一棵哈夫曼树,输出对应的哈夫曼编码和平均查找长度。并用表7.8所示的数据进行验证。
代码:
#include <iostream>
#include <malloc.h>
#include <string.h>
#define M 2*N-1
#define N 50
typedef char ElemType;
using namespace std;
typedef struct
{
char data[N]; //节点值
double weight; //权值
int parent; //双亲节点
int lchild; //左孩子节点
int rchild; //右孩子节点
} HTNode;
typedef struct
{
char cd[N]; //存放当前节点的哈夫曼编码
int start; //cd[start]~cd[n]存放哈夫曼编码
} HCode;
void CreateHT(HTNode ht[],int n)
{
int i,k,lnode,rnode;
double min1,min2;
for (i=0; i<2*n-1; i++)
ht[i].parent=ht[i].lchild=ht[i].rchild=-1;
for (i=n; i<2*n-1; i++)
{
min1=min2=32767;
lnode=rnode=-1;
for (k=0; k<=i-1; k++)
if (ht[k].parent==-1)
{
if (ht[k].weight<min1)
{
min2=min1;
rnode=lnode;
min1=ht[k].weight;
lnode=k;
}
else if (ht[k].weight<min2)
{
min2=ht[k].weight;
rnode=k;
}
}
ht[i].weight=ht[lnode].weight+ht[rnode].weight;
ht[i].lchild=lnode;
ht[i].rchild=rnode;
ht[lnode].parent=i;
ht[rnode].parent=i;
}
}
void CreateHCode(HTNode ht[],HCode hcd[],int n)
{
int i,f,c;
HCode hc;
for (i=0; i<n; i++)
{
hc.start=n;
c=i;
f=ht[i].parent;
while (f!=-1)
{
if (ht[f].lchild==c)
hc.cd[hc.start--]='0';
else
hc.cd[hc.start--]='1';
c=f;
f=ht[f].parent;
}
hc.start++;
hcd[i]=hc;
}
}
void DispHCode(HTNode ht[],HCode hcd[],int n)
{
int i,k;
double sum=0,m=0;
int j;
cout<<" 输出哈夫曼编码:\n";
for (i=0; i<n; i++)
{
j=0;
cout<<" "<<ht[i].data<<":\t";
for (k=hcd[i].start; k<=n; k++)
{
cout<<hcd[i].cd[k];
j++;
}
m+=ht[i].weight;
sum+=ht[i].weight*j;
cout<<endl;
}
cout<<"\n 平均长度="<<1.0*sum/m<<endl;
}
int main()
{
int n=15,i;
char *str[]= {"The","of","a","to","and","in","that","he","is","at","on","for","His","are","be"};
double fnum[]= {1192,677,541,518,462,450,242,195,190,181,174,157,138,124,123};
HTNode ht[M];
HCode hcd[N];
for (i=0; i<n; i++)
{
strcpy(ht[i].data,str[i]);
ht[i].weight=fnum[i];
}
cout<<endl;
CreateHT(ht,n);
CreateHCode(ht,hcd,n);
DispHCode(ht,hcd,n);
cout<<endl;
return 0;
}
运行结果: