1 #include
2 #include <string.h>
3 #define N 50 //叶子结点数
4 #define M 2*N-1 //树中结点总数
5 typedef struct
6 {
7 char data[5]; //结点值
8 int weight; //权重
9 int parent; //双亲结点
10 int lchild; //左孩子结点
11 int rchild; //右孩子结点
12 } HTNode;
13 typedef struct
14 {
15 char cd[N]; //存放哈夫曼码
16 int start;
17 } HCode;
18 void CreateHT(HTNode ht[],int n) //由ht的叶子结点构造完整的哈夫曼树
19 {
20 int i,k,lnode,rnode;
21 int min1,min2;
22 for (i=0;i<2*n-1;i++) //所有结点的相关域置初值-1
23 ht[i].parent=ht[i].lchild=ht[i].rchild=-1;
24 for (i=n;i<2*n-1;i++) //构造哈夫曼树的分支结点
25 {
26 min1=min2=32767; //lnode和rnode为最小权重的两个结点位置
27 lnode=rnode=-1;
28 for (k=0;k<=i-1;k++) //查找最小和次小的结点
29 if (ht[k].parent==-1) //只在尚未构造二叉树的结点中查找
30 {
31 if (ht[k].weight<min1)
32 {
33 min2=min1;rnode=lnode;
34 min1=ht[k].weight;lnode=k;
35 }
36 else if (ht[k].weight<min2)
37 {
38 min2=ht[k].weight;rnode=k;
39 }
40 }
41 ht[lnode].parent=i;ht[rnode].parent=i; //合并两个最小和次小的结点
42 ht[i].weight=ht[lnode].weight+ht[rnode].weight;
43 ht[i].lchild=lnode;ht[i].rchild=rnode;
44 }
45 }
46 void CreateHCode(HTNode ht[],HCode hcd[],int n) //由哈夫曼树ht构造哈夫曼编码hcd
47 {
48 int i,f,c;
49 HCode hc;
50 for (i=0;i//根据哈夫曼树构造所有叶子结点的哈夫曼编码
51 {
52 hc.start=n;c=i;
53 f=ht[i].parent;
54 while (f!=-1) //循环直到树根结点
55 {
56 if (ht[f].lchild==c) //处理左孩子结点
57 hc.cd[hc.start--]=‘0‘;
58 else //处理右孩子结点
59 hc.cd[hc.start--]=‘1‘;
60 c=f;f=ht[f].parent;
61 }
62 hc.start++; //start指向哈夫曼编码最开始字符
63 hcd[i]=hc;
64 }
65 }
66 void DispHCode(HTNode ht[],HCode hcd[],int n) //输出哈夫曼编码
67 {
68 int i,k;
69 int sum=0,m=0,j;
70 printf("输出哈夫曼编码:\n");
71 for (i=0;i)
72 {
73 j=0;
74 printf(" %s:\t",ht[i].data);
75 for (k=hcd[i].start;k<=n;k++)
76 {
77 printf("%c",hcd[i].cd[k]);
78 j++;
79 }
80 m+=ht[i].weight;
81 sum+=ht[i].weight*j;
82 printf("\n");
83 }
84 printf("平均长度=%g\n",1.0*sum/m);
85 }
86 int main()
87 {
88 int n=6,i;
89 char *str[]={"a","b","c","d","e","f"};
90 int fnum[]={45,13,12,16,9,5};
91 HTNode ht[M];
92 HCode hcd[N];
93 for (i=0;i)
94 {
95 strcpy(ht[i].data,str[i]);
96 ht[i].weight=fnum[i];
97 }
98 CreateHT(ht,n);
99 CreateHCode(ht,hcd,n);
100 DispHCode(ht,hcd,n);
101 return 1;
102 }