哈夫曼树定义如下:
构造过程为:
上面画反了,小的孩子结点在左边。
例子:
哈夫曼树的应用:哈夫曼编码
代码实现:
#include<stdio.h>
#include<stdlib.h>
//哈夫曼树有效结点个数为2n-1,n为有效结点个数
typedef struct TreeNode
{
int weight;
int parent;
int lchild;
int rchild;
}TreeNode;
typedef struct HFTree
{
struct TreeNode* data;
int length;
}HFTree;
HFTree* initTree(int* weight, int length)
{
HFTree* T = (HFTree*)malloc(sizeof(HFTree));
T->data = (TreeNode*)malloc(sizeof(TreeNode) * (2 * length - 1));
T->length = length;
for (int i = 0; i < length; i++)
{
T->data[i].weight = weight[i];
T->data[i].parent = 0;
T->data[i].lchild = -1;
T->data[i].rchild = -1;
}
return T;
}
int* selectMin(HFTree* T)
{
int Min = 10000;
int secondMin = 10000;
int minIndex;
int secondIndex;
for (int i = 0; i < T->length; i++)
{
if (T->data[i].parent == 0)
{
if (T->data[i].weight < Min)
{
Min = T->data->weight;
minIndex = i;
}
}
}
for (int i = 0; i < T->length; i++)
{
if (T->data[i].parent == 0 && i!= minIndex)
{
if (T->data[i].weight < secondMin)
{
secondMin = T->data->weight;
secondIndex = i;
}
}
}
int* res = (int*)malloc(sizeof(int) * 2);
res[0] = minIndex;
res[1] = secondIndex;
return res;
}
void creatHFTree(HFTree* T)
{
int* res;
int Min;
int SecondMin;
int length = T->length * 2 - 1;
for (int i = T->length; i < length; i++)
{
res = selectMin(T);
Min = res[0];
SecondMin = res[1];
T->data[i].weight = T->data[Min].weight + T->data[SecondMin].weight;
T->data[i].lchild = Min;
T->data[i].rchild = SecondMin;
T->data[i].parent = 0;
T->data[Min].parent = i;
T->data[SecondMin].parent = i;
T->length++;
}
}
void preOeder(HFTree* T, int index)
{
if (index != -1)
{
printf("%d ", T->data[index].weight);
preOeder(T, T->data[index].lchild);
preOeder(T, T->data[index].rchild);
}
}
int main()
{
int weight[4] = { 1,2,3,4 };
HFTree* T = initTree(weight,4);
//int* res = selectMin(T);
//printf("res[0]=%d,res[1]=%d", res[0], res[1]);
creatHFTree(T);
preOeder(T, T->length - 1);
system("pause");
return 0;
}
测试结果: