刚开始时毫无思路的,不过最后自己翻了书,自己还是看懂了的。既然是仿着书写的就不自己写好多 直接上图和程序吧。
# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
# define MaxValue 10000
# define MaxBit 4
# define MaxN 10
typedef struct
{
int weight; //权值
int flag; //标记
int parent; //双亲节点下标
int leftchild; //左孩子下标
int rightchild; //右孩子下标
}HaffNode; //哈夫曼树的结点结构
typedef struct
{
int bit[MaxN]; //数组
int start; //编码的起始下标
int weight; //字符的权值
}Code; //哈夫曼编码的及污垢
//建立叶子结点个数为n,权值数组为weight的哈夫曼树haffTree
void Haffman(int weight[],int n,HaffNode haffTree[])
{
int i,j,m1,m2,x1,x2;
//哈夫曼树haffTree初始化,n个叶节点的二叉树共有2n-1
for(i = 0;i < 2*n -1;i ++)
{
if(i < n)
haffTree[i].weight = weight[i];
else
haffTree[i].weight = 0;
haffTree[i].parent = -1;
haffTree[i].flag = 0;
haffTree[i].leftchild = -1;
haffTree[i].rightchild = -1;
}
//构造哈夫曼树haffTree的n-1个非叶结点
for(i = 0;i < n-1;i ++)
{
m1 = m2 = MaxValue;
x1 = x2 = 0;
//找出权值最小和次小的子树
for(j = 0;j < n+i;j ++)
{
if(haffTree[j].weight < m1 && haffTree[j].flag == 0)
{
m2 = m1;
x2 = x1;
m1 = haffTree[j].weight;
x1 = j;
}
else
if(haffTree[j].weight < m2 && haffTree[j].flag == 0)
{
m2 = haffTree[j].weight;
x2 = j;
}
}
//将找出的两棵权值最小和次小的子树合并成一棵子树
haffTree[x1].parent = n + i;
haffTree[x2].parent = n + i;
haffTree[x1].flag = 1;
haffTree[x2].flag = 1;
haffTree[n+i].weight = haffTree[x1].weight + haffTree[x2].weight;
haffTree[n+i].leftchild = x1;
haffTree[n+i].rightchild = x2;
}
}
//由n个结点的哈夫曼树haffTree构造哈夫曼编码haffCode
void HaffmanCode(HaffNode haffTree[],int n,Code haffCode[])
{
Code *cd = (Code *)malloc(sizeof(Code));
int i,j,child,parent;
//求n个叶结点的哈夫曼编码
for(i = 0;i < n; i ++)
{
cd->start = n-1; //不等长编码的最后一位为n-1
cd->weight = haffTree[i].weight; //取得编码对应的权值
child = i;
parent = haffTree[child].parent;
//由叶结点向上直到根结点
while(parent != -1)
{
if(haffTree[parent].leftchild == child)
cd->bit[cd->start] = 0; //左孩子分支编码为0
else
cd->bit[cd->start] = 1; //右孩子分支编码为1
cd -> start --;
child = parent;
parent = haffTree[child].parent;
}
for(j = cd->start+1;j < n;j ++)
haffCode[i].bit[j] = cd->bit[j]; //保存每个叶结点的编码
haffCode[i].start = cd->start+1; //保存也结点编码的起始位
haffCode[i].weight = cd->weight; //保存编码对应的权值
}
}
int main()
{
int i,j,n=4;
int weight[] = {1,3,5,7};
HaffNode *myHaffTree = (HaffNode *)malloc(sizeof(HaffNode)*(2*n-1));
Code *myHaffCode = (Code *)malloc(sizeof(Code)*n);
if(n > MaxN)
{
printf("给出的n越界,修改MaxN.\n");
exit(1);
}
Haffman(weight,n,myHaffTree);
HaffmanCode(myHaffTree,n,myHaffCode);
for(i = 0;i < n;i ++)
{
printf("weight = %d Code = ",myHaffCode[i].weight);
for(j = myHaffCode[i].start;j < n;j ++)
printf("%d",myHaffCode[i].bit[j]);
printf("\n");
}
return 0;
}
现在已经发现自己好多的问题了 继续查漏补缺!!!!------Dash