最近在学习哈夫曼树相关的内容,相关的代码贴到下面。哈夫曼树不唯一,仅供参考
Select函数的实现,复杂度较高,尚可优化。
#define _CRT_SECURE_NO_WARNINGS//仅visual studio需要添加该宏
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char** HuffmanCode;//哈夫曼编码
typedef struct {
int weight;
int parent, lchild, rchild;
}HTnode, * HuffmanTree;
void Select(HuffmanTree HT, int pos, int* s1, int* s2)
{
int min1 = 10000;
int min2 = 10000;//定义一个超大的数,以使树的权永远小于该数
for (int i = 1; i <= pos; i++)
{
if (HT[i].parent == 0 && HT[i].weight < min1)
{
min1 = HT[i].weight;
*s1 = i;//带回最小值的下标
}
}
for (int j = 1; j <= pos; j++)
{
if (j != (*s1) && HT[j].parent == 0)//跳过第一轮的最小值,从而找次小值
{
if (HT[j].weight < min2)
{
min2 = HT[j].weight;
(*s2) = j;
}
}
}
}
void CreateHuffmanTree(HuffmanTree* HT, int n)
{
if (n <=1)return;
int m = 2 * n - 1;//数组共2n-1个元素
*HT = (HuffmanTree)malloc(sizeof(HTnode) * (m + 1));//0号单元未用,HT[m]表示根结点
//初始化2n-1元素的lchild、rchild、parent设置成0
for (int i = 1; i <= m; i++)
{
(*HT)[i].parent = 0;
(*HT)[i].lchild = 0;
(*HT)[i].rchild = 0;
}
for (int i = 1; i <= n; i++)//输入前n个元素的weight
{
scanf("%d", &((*HT)[i].weight));
//fflush(stdin);
}
/*初始化完成,下面进行HuffmanTree构建*/
for (int i = n + 1; i <= m; i++)
{
int s1, s2;
Select(*HT, i - 1, &s1, &s2);
(*HT)[s1].parent = i;
(*HT)[s2].parent = i;
(*HT)[i].weight = (*HT)[s1].weight + (*HT)[s2].weight;
(*HT)[i].lchild = s1;
(*HT)[i].rchild = s2;
}
}
void CreateHuffmanCode(HuffmanTree HT, HuffmanCode*HC,int n)
{
//定义一个指针数组,每个成员指向一个包含哈夫曼编码的字符串数组,下标从1开始,故申请n+1
*HC = (HuffmanCode)malloc(sizeof(char*)*(n+1));
//定义一个cd字符串数组,存放写好的哈夫曼编码
char* cd = (char*)malloc(sizeof(char) * (n));
cd[n - 1] = '\0';//cd最后存放字符串结束标志
if (*HC&&cd)
{
for (int i = 1; i <= n; i++)
{
int start = n - 1;//因为路径是叶子到根,故从n-1开始
int f = HT[i].parent;//查看第i个结点的parent,并将双亲下标保存在f中
int c = i;//定义一个c保存当前结点的下标
while (f != 0)//循环条件是双亲的parent不为0,也就是不为根结点
{
start--;//循环开始,此时start值为n-2
if (HT[f].lchild == c)//当前孩子是其双亲的左孩子
{
cd[start] = '0';//赋值为0
}
else {
cd[start] = '1';
}
c = f;//找上一层
f = HT[f].parent;
}
//为HC[i]这个指针数组分配一个n-start大小的空间,注意!!!此处(*HC)[i]必须带括号!!!,下面同
(*HC)[i] = (char*)malloc(sizeof(char) * (n - start));
//将cd中的哈夫曼编码copy到上面的数组中
strcpy((*HC)[i], &cd[start]);
}
free(cd);
}
}
void Print_HT_HC(HuffmanTree HT, HuffmanCode HC,int n)
{
printf("HuffmanTree结构:\n");
printf("序号 权重 双亲 左孩子 右孩子\n");
for (int i = 1; i <= 2*n-1; 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("Huffman编码结构:\n");
for (int i = 1; i <= n; i++)
{
printf("%s\n", HC[i]);
}
}
int main()
{
HuffmanTree HT;
HuffmanCode HC;
int n;
printf("请输入要建立的HuffmanTree的结点数:\n");
scanf("%d", &n);
fflush(stdin);
printf("请输入要建立的HuffmanTree的权重(以空格隔开):\n");
CreateHuffmanTree(&HT,n);
CreateHuffmanCode(HT,&HC,n);
Print_HT_HC(HT, HC,n);
return 0;
}