#include<stdio.h>
#define INFINITY 35000
#define MAXLEAF 30
#define MAXNODE MAXLEAF*2-1
#define MAXBIT 10
typedef struct {
int weight;
int parent,lchild,rchild;
}HTNode;
typedef struct{
int bit[MAXBIT];
int start;
}HTCode;
void print_HuffmanTree(HTNode HuffNode[],int n);
void Init_HuffmanTree(HTNode HuffNode[],int n);
void HuffmanTree(HTNode HuffNode[],int n);
void HuffmanCode()
{
HTNode HuffNode[MAXNODE];
HTCode HuffCode[MAXLEAF],cd;
int i,j,c,p,n;
}
int main()
{
HTNode huffTree[MAXNODE];
Init_HuffmanTree(huffTree,MAXNODE);
HuffmanTree(huffTree,5);
print_HuffmanTree(huffTree,5);
return 0;
}
void print_HuffmanTree(HTNode HuffNode[],int n)
{
int i;
printf("-------------------------------------------------\n");
for(i=0;i<n;i++)
{
printf("HuffNode[%2d] w:%4d parent:%2d lchild:%2d rchild:%2d\n",
i,HuffNode[i].weight,HuffNode[i].parent,
HuffNode[i].lchild,HuffNode[i].rchild);
}
}
void Init_HuffmanTree(HTNode HuffNode[],int n)
{
int i=0;
for(i=0;i<n;i++)
{
HuffNode[i].weight=0;
HuffNode[i].parent=0;
HuffNode[i].lchild=0;
HuffNode[i].rchild=0;
}
}
void HuffmanTree(HTNode HuffNode[],int n)
{
int i,j,m1,m2,x1,x2;
for(i=0;i<2*n-1;i++)
{
HuffNode[i].weight=0;
HuffNode[i].parent=-1;
HuffNode[i].lchild=-1;
HuffNode[i].rchild=-1;
}
//print_HuffmanTree(HuffNode,n);
for(i=0;i<n;i++)
{
printf("请输入第%d个节点的权重:",i+1);
scanf("%d",&HuffNode[i].weight);
}
for(i=0;i<n-1;i++)
{
m1=m2=INFINITY;
x1=x2=-1;
for(j=0;j<n+i;j++)
{
if(HuffNode[j].weight<m1 && HuffNode[j].parent==-1)
{
//printf("1 if: i=%d,j=%d:m1=%d,m2=%d,x1=%d,x2=%d\n",i,j,m1,m2,x1,x2);
m2=m1;
x2=x1;
m1=HuffNode[j].weight;
x1=j;
//printf("2 if: i=%d,j=%d:m1=%d,m2=%d,x1=%d,x2=%d\n",i,j,m1,m2,x1,x2);
}
else if(HuffNode[j].weight<m2 && HuffNode[j].parent==-1)
{
//printf("1 else if: i=%d,j=%d:m1=%d,m2=%d,x1=%d,x2=%d\n",i,j,m1,m2,x1,x2);
m2=HuffNode[j].weight;
x2=j;
//printf("2 else if: i=%d,j=%d:m1=%d,m2=%d,x1=%d,x2=%d\n",i,j,m1,m2,x1,x2);
}
}//for j ends here
HuffNode[x1].parent=n+i;
HuffNode[x2].parent=n+i;
HuffNode[n+i].weight=HuffNode[x1].weight+HuffNode[x2].weight;
HuffNode[n+i].lchild=x1;
HuffNode[n+i].rchild=x2;
///print_HuffmanTree(HuffNode,n+i+1);
}//for i ends here
}