源代码:
//哈夫曼树算法
#include <stdio.h>
#include <stdlib.h>
#define MAX_VALUE 20
typedef struct // 一个结点
{
int Weight; bool flag;
int Parent, LChild, RChild;
} HuffNode, *pHuffNode;
//---------------------------------------
typedef struct // Huffman 树
{
int n; // 权个数
int root; // 树根在数组中的位置
HuffNode *Huf; // 数组首地址(动态分配)
} HuffTree, *pHuffTree;
int main()
{
HuffTree Tree;
int arr[4] = { 1, 5, 4, 8 };
int n = 4;
if (n < 1) { return NULL; }
else
{
Tree.n = n; // Tree.root = -1 ;
Tree.root = -1;
Tree.Huf = (pHuffNode)malloc((2 * n - 1)* sizeof(HuffNode));
for (int i = 0; i < 2 * n - 1;)
{
Tree.Huf[i].flag = false; // i 结点未加入树中
Tree.Huf[i].Weight = (i < n) ? arr[i] : 0;
Tree.Huf[i].Parent = -1;
Tree.Huf[i].LChild = -1;
Tree.Huf[i].RChild = -1;
i++;
}
}
int i, j, m1, m2, x1, x2;
for (i = n; i < 2 * n - 1; i++) // 遍历节点
{
m1 = m2 = MAX_VALUE;
x1 = x2 = -1; // m1<=m2
for (j = 0; j < i; j++) // 2n-1个结点
{
if (Tree.Huf[j].flag != false) { continue; } // j 结点未加入树中
if (Tree.Huf[j].Weight < m1)
{
m2 = m1;
x2 = x1;
m1 = Tree.Huf[j].Weight;
x1 = j;
}
else if (Tree.Huf[j].Weight < m2)
{
m2 = Tree.Huf[j].Weight;
x2 = j;
}
}
Tree.Huf[x1].Parent = i;
Tree.Huf[x2].Parent = i;
Tree.Huf[x1].flag = true;
Tree.Huf[x2].flag = true;
Tree.Huf[i].Weight = Tree.Huf[x1].Weight + Tree.Huf[x2].Weight;
Tree.Huf[i].LChild = x1;
Tree.Huf[i].RChild = x2;
}
for (int i = 0; i < 2*n - 1;i++)
{
printf("%d ", Tree.Huf[i].Weight);
}
free(Tree.Huf);
system("pause");
return 0;
}