哈夫曼树:
定义:
typedef struct
{unsigned int weight;
unsigned int parent,lchild,rchild;
}htnode,*huffmantree;
typedef char *huffmancode
求哈夫曼树:
huffmantree crt_huffmantree(int *w,int n)
{huffmantree ht;
m=2*n-1;
ht=(huffmantree)malloc((m+1)*sizeof(htnode));
for(p=ht,i=1;i<=n;i++,p++,w++) *p={*w,0,0,0};
for(;i<=m;i++,p++) *p={0,0,0,0};
for(i=n+1;i<=m;i++)
{select(ht,i-1,s1,s2);
ht[s1].parent=i;ht[s2].parent=i;
ht.lchild=s1;ht.rchild=s2;
ht.weight=ht[s1].weight+ht[s2].weight;
}
return ht;
}
从叶子到根逆向求每个字符的哈夫曼编码:
huffmancode get_huffmancode(huffmantree ht,int n)
{hc=(huffmancode)malloc((n+1)*sizeof(char));
cd=(char*)malloc(n*sizeof(char));
cd[n-1]="\0";
for(i=1;i<=n;i++)
{start=n-1;
for(c=i,f=ht.parent;f!=c;f=ht[f].parent)
if(ht[f].lchild==c) cd[--start]="0";
else cd[--start]="1";
hc=(char*)malloc((n-start)*sizeof(char));
strcpy(hc,&cd[start]);
}
free(cd);
return hc;
} |