我的第一篇博客
哈夫曼树的建立与编码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int n;
int m;
struct tree
{
int weight;
int parent;
int Lchild;
int Rchild;
}ht[];
struct coder
{
int data;
char code[10];
}hc[];
void select(struct tree ht[],int k,int *s1,int *s2)
{
int i;
for(i=1; i<=k ; ++i)
{
if(ht[i].parent == 0)
break;
}
*s1 = i;
for(i=1; i<=k; ++i)
{
if(ht[i].parent==0 && ht[i].weight<ht[*s1].weight)
*s1 = i;
}
for(i=1; i<=k; ++i)
{
if(ht[i].parent==0 && i!=*s1)
break;
}
*s2 = i;
for(i=1; i<=k; ++i)
{
if(ht[i].parent==0 && i!=*s1 && ht[i].weight<ht[*s2].weight)
*s2 = i;
}
}
creat()
{
struct tree *ht;
struct coder *hc;
int i,j,s1,s2,start,c,p;
char *cd;
ht=(struct tree*)malloc((n+1)*sizeof(struct tree));
hc=(struct coder*)malloc((n+1)*sizeof(struct coder));
cd=(char *)malloc(m*sizeof(char));
cd[n-1]='\0';
//建树
for(i=1;i<=m;i++)
{
printf("请输入数字:");
scanf("%d",&j);
ht[i].weight =j;
ht[i].parent =0;
ht[i].Lchild =0;
ht[i].Rchild =0;
}
for(i=m+1;i<n+1;i++)
{
ht[i].weight =0;
ht[i].parent =0;
ht[i].Lchild =0;
ht[i].Rchild =0;
}
for(i=m+1;i<n+1;i++)
{
select(ht,i-1,&s1,&s2);
ht[i].weight =ht[s1].weight +ht[s2].weight ;
ht[i].Lchild =s1;
ht[i].Rchild =s2;
ht[s1].parent =i;
ht[s2].parent =i;
}
for(i=1;i<n+1;i++)
printf("%2d. %3d %3d %3d %3d \n",i,ht[i].weight ,ht[i].parent ,ht[i].Lchild ,ht[i].Rchild) ;
//编码
for(i=1;i<=m;i++)
{
start=n-1;
c=i;
p=ht[i].parent;
while(p!=0)
{
--start;
if(ht[p].Lchild ==c)
cd[start]='0';
else
cd[start]='1';
c=p;
p=ht[p].parent ;
}
strcpy(hc[i].code,&cd[start]);
}
for(i=1;i<=m;i++)
printf("%d--%s\n",ht[i].weight ,hc[i].code );
}
main()
{
printf("节点数:");
scanf("%d",&m);
n=2*m-1;
creat(n,m);
}
本文详细介绍了哈夫曼树的建立过程及其在数据编码中的应用,通过实例展示了如何构建哈夫曼树并为不同字符分配最优编码。
2万+

被折叠的 条评论
为什么被折叠?



