#define _CRT_SECURE_NO_WARNINGS 1
#include<stdlib.h>
#include<stdio.h>
#define N 30 //叶子结点的最大值
#define M 2*N-1 // 结点总数
typedef struct HTNode
{
int weight;
int parent;
int Lchild;
int Rchild;
int flag;
}HTNode,HuffmanTree[M+1];//HuffmanTree[M+1] 0号单元不使用
//初始化
void InitHuffmanTree(HuffmanTree ht, int n)//初始哈夫曼树
{
//1-n是叶子结点 n+1 - m 是非叶子结点
//初始化叶子节点
for (int i = 1; i <= n; i++)
{
ht[i].Lchild = 0;
ht[i].Rchild = 0;
ht[i].weight = 0;
ht[i].parent = 0;
ht[i].flag = 0;
scanf("%d", &ht[i].weight);//赋值权值
}
int m = 2 * n - 1;//总结点数值
//初始化非叶子节点
for (int i = n + 1; i <= m; i++)
{
ht[i].Lchild = 0;
ht[i].Rchild = 0;
ht[i].weight = 0;
ht[i].parent = 0;
ht[i].flag = 0;
}
}
int select(HuffmanTree ht, int n)
{
int i, temp, min;
//拿到第一个权值的信息去比较下面
for (i = 1; i <= n; i++)
{
if (ht[i].flag == 0)
{
temp = ht[i].weight;//记录权值
min = i;//记录下标索引
break;
}
}
for (i = 1; i <= n; i++)
{
if (ht[i].flag == 0 && temp > ht[i].weight)//把temp权值小的才进来
{
//把更小的权值赋给temp
temp = ht[i].weight;
min = i;
}
}
ht[min].flag = 1;//只要这里flga赋为1,找次最小权值的时候就不会重复
return min;
}
void CreateHuffmanTree(HuffmanTree ht, int n)
{
//n+1 到 m 之间
for (int i = n + 1; i <= (2 * n - 1); i++)
{
int s1 = select(ht, i - 1);//i-1是相当于是n,意思是把所有叶子结点的总数传到select
int s2 = select(ht, i - 1);
ht[i].weight = ht[s1].weight + ht[s2].weight;
ht[s1].parent = i;
ht[s2].parent = i;
ht[i].Lchild = s1;
ht[i].Rchild = s2;
}
}
void printHuffmanTree(HuffmanTree ht, int n)
{
printf("结点 weigh parent Lchild Rchild\n");
for (int i = 1; i <= n; i++)
{
printf("%d\t%d\t%d\t%d\t%d\n", i, ht[i].weight, ht[i].parent, ht[i].Lchild, ht[i].Rchild);
}
printf("\n");
}
void freeHuffmanTree(HuffmanTree ht)
{
}
int main()
{
HuffmanTree HT;
int n;//所需的叶子结点数
printf("请输入初始的叶子结点个数\n");
scanf("%d", &n);
printf("请输入%d个叶子结点分别的权值\n", n);
//初始化
InitHuffmanTree(HT, n);
printf("初始哈夫曼树如下\n");
printHuffmanTree(HT, 2 * n - 1);
//构造哈夫曼
CreateHuffmanTree(HT, n);
printf("构建后的哈夫曼树如下\n");
printHuffmanTree(HT, 2 * n - 1);
return 0;
}