#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
unsigned int weight;
unsigned int parent,lchild,rchild;
}HTNode,*HuffmanTree;
typedef char **HuffmanCode;
int min(HuffmanTree t,int i)
{
int j,flag;
unsigned int k=UINT_MAX;
for(j=1;j<=i;j++)
{
if(t[j].weight<k && t[j].parent==0)
k=t[j].weight,flag=j;
}
t[flag].parent=1;
return flag;
}
void select(HuffmanTree t,int i,int &s1,int &s2)
{
int j;
s1=min(t,i);//注意:这里s2,s2应该是不用的
s2=min(t,i);
if(s1>s2)
{
j=s1;
s1=s2;
s2=j;
}
}
void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,int *w,int n)
{
int m,i,s1,s2,start;
unsigned c,f;
HuffmanTree p;
char *cd=NULL;
if(n<=1)//没有节点的时候就返回空值
return;
m=2*n-1;
HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode));
for(p=HT+1,i=1;i<=n;++i,++p,++w)
{
(*p).weight=*w;
(*p).parent=0;
(*p).lchild=0;
(*p).rchild=0;
}
for( ;i<=m;++i,++p)//为什么这一步从n到m进行双亲的赋值
(*p).parent=0;
for(i=n+1;i<=m;++i)//建立赫夫曼树
{
select(HT,i-1,s1,s2);
HT[s1].parent=HT[s2].parent=i;//这一步是什么意思???
HT[i].lchild=s1;
HT[i].rchild=s2;
HT[i].weight=HT[s1].weight + HT[s2].weight;
}
HC=(HuffmanCode)malloc((n+1)*sizeof(char *));//不明白这里为什么是n+1;
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));//这里又为什么是n-start??????
strcpy(HC[i],&cd[start]);
}
free(cd);
}
int main()
{
HuffmanTree HT=NULL;//定义一个指针
HuffmanCode HC;//二级指针
int *w,n,i;
printf("Please input the number of all the node digit:");
scanf("%d",&n);
w=(int *)malloc(n*sizeof(int));
printf("Please input the %d node digits:\n",n);
for(i=0;i<n;i++)
scanf("%d",w+i);
HuffmanCoding(HT,HC,w,n);
for(i=1;i<=n;i++)
puts(HC[i]);
getch();
}
我只知道建立赫夫曼树的方法,却不是很理解代码的意思,请大家给我详细解释下,非常感谢