#include<stdio.h>
#include<stdlib.h>
typedef struct{
int weight;
int parent,lc,rc;
}HTNode,*HuffmanTree;
HTNode HT[100];
int min(int n)
{
int min;//用于存放最小值的下标
int min_t;//用于存放最小值的权值
min_t=HT[0].weight;//初始化权值weight的值
int i=1;
while(HT[i].parent!=0)//此时已经找出了第一个的最小值,while循环用于找第二个最小值
i++;
min_t=HT[i].weight;
min=i;
for(i=1;i<=n;i++)
{
if(HT[i].weight<min_t&&HT[i].parent==0)
{
min_t=HT[i].weight;
min=i;
}
}
HT[min].parent=1;
return min;
}
void select(int n,int *min1,int *min2)//指针变量做参数,形参变化影响实参
{
*min1=min(n);
*min2=min(n);
if(*min2<*min1)//总之min1值一直是要小于min2的值
{
int temp;
temp=*min1;
*min1=*min2;
*min2=temp;
}
}
void CreatHuffmanTree(int n)
{
if(n<=1)
return;
int m=2*n-1;
for(int i=1;i<=m;i++)
{
HT[i].parent=0;
HT[i].lc=0;
HT[i].rc=0;
}
printf("please enter the weight of leaves\n");
for(int i=1;i<=n;i++)
{
scanf("%d",&HT[i].weight);
}
for(int i=n+1;i<=m;i++)
{
int s1,s2;
select(i-1,&s1,&s2);
HT[s1].parent=i;
HT[s2].parent=i;
HT[i].lc=s1;
HT[i].rc=s2;
HT[i].weight=HT[s1].weight+HT[s2].weight;
}
}
void show(int n)
{
for(int i=1;i<=2*n-1;i++)
printf("weight is %2d parents is %2d ;children is %2d %2d\n",HT[i].weight,HT[i].parent,HT[i].lc,HT[i].rc);
printf("(Where the node is 0 means there is no node.)\n");
}
int main()
{
printf("Please enter the number of leaves:");
int n;
scanf("%d", &n);
CreatHuffmanTree(n);
show(n);
return 0;
}
运行截图