哈夫曼编码:
根据给定的哈夫曼树,从每个叶子节点出发回溯到树根,逆向找出最优二叉树中叶子节点的编码。
代码如下:
#define MAXLEAFNUM 50
#include<malloc.h>
#include<cstring>
typedef struct node{
char ch;//节点表示的字符
int weight;//权值
int parent;//父节点下标(默认为零)
int lchild,rchild;//左右孩子下标(默认为零)
}HuffmanTree[2*MAXLEAFNUM];
typedef char* HuffmanCode[MAXLEAFNUM+1];
/*从HT中选择parent为0且weight最小的两棵树,其序列号为s1和s2*/
void select(HuffmanTree HT,int n,int &s1,int &s2)
{
int i,min2;
int min1=min2=32768;
for(i=0;i<n;i++)
{
if(HT[i].parent==0)
{
if(HT[i].weight<min1){
min2=min1;
min1=HT[i].weight;
}else if(HT[i].weight<min2)
{
min2=HT[i].weight;
}
}
}
s1=min1;
s2=min2;
}
/*构造最优二叉树*/
void createHTree(HuffmanTree HT,char *c,int *w,int n)
{
int i,s1,s2;//
if(n<=1)return;
for(i=1;i<=n;i++)//初始化
{
HT[i].ch=c[i-1]; HT[i].weight=w[i-1];
HT[i].parent=HT[i].lchild=HT[i].rchild=0;
}
for(;i<2*n;i++)//
{
HT[i].parent=HT[i].lchild=HT[i].rchild=0;
}
for(i=n+1;i<2*n;i++)
{
select(HT,i-1,s1,s2);
HT[s1].parent=i; HT[s2].parent=i;
HT[i].lchild=s1; HT[i].rchild=s2;
HT[i].weight=HT[s1].weight+HT[s2].weight;
}
}
/*编码*/
void HuffmanCoding(HuffmanTree HT,HuffmanCode HC,int n)
{//n个叶子结点在哈夫曼树HT中的下标为1~n,第i(1<=i<=n)个叶子的编码存放HC[i]中
char *cd;int i,start,c,f;
if(n<=1) return;
cd=(char*)malloc(n*sizeof(char)); cd[n-1]='\0';
for(i=1;i<=n;i++)
{
start=n-1;
for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent)
if(HT[f].lchild==c) cd[--start]='0';
else cd[--start]='1';
HC[i]=(char*)malloc((n-start)*sizeof(char));
strcpy(HC[i],&cd[start]);
}
free(cd);
}
/*用最优二叉树进行译码*/
void Decoding(HuffmanTree HT,int n,char *buff)
{
int p=2*n-1;
while(*buff)
{
if((*buff)=='0') p=HT[p].lchild;
else p=HT[p].rchild;
if(HT[p].lchild==0&&HT[p].lchild==0)
{
pritnf("%c",HT[p].ch);
p=2*n-1;
}
buff++;
}
}
int main()
{
return 0;
}