哈夫曼树和哈夫曼编码 C语言版的

哈夫曼树和哈夫曼编码 C语言版的

typedef struct{
int weight;
int lchild;
int rchild;
int parent;
}Haftree;

typedef struct{
int code[30];
int start;
}Hafcode;

void hafencode(Haftree *t)
{
int n;
int i,j,x1,x2,m1,m2;
Hafcode code[300];
Hafcode tmp;
int c,start,p;
printf("请输入叶子节点数胡桥:");
scanf("%d",&n);
getchar();
for(i=0;i<2*n-1;i++)
{
t[i].parent=-1;
t[i].weight=0;
t[i].lchild=t[i].rchild=0;
}
printf("请输入叶子节点的权值:");
for(i=0;i scanf("%d",&t[i].weight);
for(i=0;i {
x1=x2=65535;
m2=m1=0;
for(j=0;j<好做派n+i;j++)
{
if(t[j].parent==-1&&t[j].weight {
x2=x1;
x1=t[j].weight;
m2=m1;
m1=j;
}
else if(t[j].parent==-1&&t[j].weight {
x2=t[j].weight;
m2=j;
}
}
t[n+i].weight=x1+x2;
t[m1].parent=n+i;
t[m2].parent=n+i;
t[n+i].lchild=m1;
t[n+i].rchild=m2;
}
for(i=0;i<友贺2*n-1;i++)
{
printf("%d ",t[i].weight);
}
printf("\n");
for(i=0;i {
c=t[i].parent;
tmp.start=n-1;
p=i;
while(c!=-1)
{
if(haftree[c].lchild==p)
{
tmp.code[tmp.start]=0;
}
else if(haftree[c].rchild==p)
{
tmp.code[tmp.start]=1;
}
tmp.start--;
p=c;
c=t[p].parent;
}
for(j=tmp.start+1;j code[i].code[j]=tmp.code[j];
code[i].start=tmp.start+1;
}
for(i=0;i {
for(j=code[i].start+1;j printf("%d ",code[i].code[j]);
printf("\n");
}
}
← 上一篇: 下一篇: →