问题描述:树和二叉树的基本运算实现
设计一个程序exp7-6.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 |
算法设计:哈弗曼树建立和哈弗曼编码的创建
完成时间:2017年6月22日
代码:
/*
问题描述:树和二叉树的基本运算实现
作者:何知令
完成时间:2017年6月22日
*/
#include <stdio.h>
#define N 30
typedef struct
{
char data[5];
double weight;
int parent;
int lchild;
int rchild;
} HTNode;
typedef struct
{
char cd[N/2];
int start;
} HCode;
void CreatHt(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 CreatHCode(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;
}
hcd[i]=hc;
}
}
void DispHCode(HTNode ht[],HCode hcd[],int n)
{
int i,k;
double sum=0,m=0;
int j;
printf("输出哈夫曼编码:\n"); //输出哈夫曼编码
for (i=0; i<n; i++)
{
j=0;
printf("%s:\t",ht[i].data);
for (k=hcd[i].start; k<=n; k++)
{
printf("%c",hcd[i].cd[k]);
j++;
}
m+=ht[i].weight;
sum+=ht[i].weight*j;
printf("\n");
}
printf("平均长度%f",1.0*sum/m-1);
}
int main()
{
HTNode ht[N]= {{"the",1192},{"of",677},{"a",541},{"to",518},{"and",462},{"in",450},{"that",242},{"he",195},{"is",190},{"at",181},{"on",174,},{"for",157},{"His",138},{"are",124},{"be",123}};
HCode hcd[N/2];
CreatHt(ht,N/2);
CreatHCode(ht,hcd,N/2);
DispHCode(ht,hcd,N/2);
return 0;
}
程序运行结果展示:
知识点总结:哈弗曼树的建立和哈弗曼编码的实现
学习心得:...