/*
哈夫曼树
*/
#include<stdio.h>
#include<stdio.h>
#define n 5 //叶子结点个数
#define m 2*n-1 //hufftree的结点个数
//定义构造hufftree的结构体
typedef struct
{
char data;
int weight;
int parent, lchild, rchild;
}huffnode;
//定义输出哈夫曼编码的结构体
typedef struct
{
char path[m];
int start;
}huffcode;
//构造哈夫曼树
void create_hufftree(huffnode tree[]);
//编码
void create_huffcode(huffnode tree[]);
//打印函数
void print_hufftree(huffnode tree[]);
int main()
{
huffnode tree[m+1]; //0号单元不用
create_hufftree(tree);
print_hufftree(tree);
create_huffcode(tree);
//printf("2");
return 0;
}
void create_hufftree(huffnode tree[])
{
int i, k, l, r, small1, small2;
for(i=1; i<=m; i++) //对每个结点进行初始化
{
tree[i].parent = tree[i].lchild = tree[i].rchild = 0;
tree[i].data =' ';
}
for(i=1; i<=n; i++) //输入n个结点的信息
{
if(i!=1) getchar();
printf("The value of %dth element: ", i);
scanf("%c", &tree[i].data);
printf("The weight of %dth element: ", i);
scanf("%d", &tree[i].weight);
}
for(i=n+1; i<=m; i++) //构造huffman树
{
small1 = small2 = 32767;
l = r = 0; //l和r为最小权重的两个结点位置
for(k=1; k<=i-1; k++)
{
if(tree[k].parent == 0)
if(tree[k].weight<small1)
{
small2 = small1;
r = l;
small1 = tree[k].weight;
l = k;
}
else if(tree[k].weight<small2)
{
small2 = tree[k].weight;
r = k;
}
}
tree[l].parent = i;
tree[r].parent = i;
tree[i].weight = tree[l].weight + tree[r].weight;
tree[i].lchild = l;
tree[i].rchild = r;
}
}
void create_huffcode(huffnode tree[])
{
int i, k, mid, p;
huffcode hcd[n], node;
printf("1");
for(i=1; i<=n; i++)
{
//printf("3");
node.start = n+1;
mid = i;
p = tree[i].parent;
//printf("assas");
while(p!=0)
{
//printf("4");
if(tree[p].lchild == mid)
node.path[node.start] = '0';
else
node.path[node.start] = '1';
node.start--;
mid = p;
p = tree[p].parent;
}
hcd[i] = node;
}
printf("Output Huffman code:
");
for(i=1; i<=n; i++)
{
printf("%c:", tree[i].data);
for(k=hcd[i].start; k<=n; k++)
printf("%c", hcd[i].path[k]);
printf("
");
}
}
/*
void create_huffcode(huffnode tree[])
{
int i, k, mid, p;
huffcode hcd[5], node;
for(i=1; i<=5; i++)
{
node.start = 6;
mid = i;
p = tree[i].parent;
while(p!=0)
{
if(tree[p].lchild == mid)
node.path[--node.start]='0';
else node.path[--node.start]='1';
mid = p;
p = tree[p].parent;
}
hcd[i] = node;
}
printf("Output Huffman code:
");
for(i=1; i<=n; i++)
{
printf("%c:", tree[i].data);
for(k=hcd[i].start; k<=n; k++)
printf("%c", hcd[i].path[k]);
printf("
");
}
}*/
void print_hufftree(huffnode tree[]) /*输出整棵哈夫曼树*/
{
int i;
printf("huffman tree:
");
printf("i Vlue Parent Lchild Richild Weight
");
for(i=m; i>=1; i--)
{
printf("%d ", i);
printf("%c ", tree[i].data);
printf("%d ", tree[i].parent);
printf("%d ", tree[i].lchild);
printf("%d ", tree[i].rchild);
printf("%d ", tree[i].weight);
printf("
");
}
}