说明:
构建哈夫曼树:
1、从结点列表中找到第一小和第二小的结点,组成一棵树,组成新树的父结点权值为两结点权值之和
2、将新树放入结点列表中,重复操作,直到列表中只有一个结点
结构体:
#include <windows.h>
#include <stdio.h>
typedef struct TreeNode
{
int weight;
int parent;
int lchild;
int rchild;
}TreeNode;
typedef struct HFTree
{
TreeNode *data;
int length;
}HFTree;
HFTree *InitTree(int *weight,int length);
int *selectMin(HFTree *T);
void CreatHF_tree(HFTree *T);
void Preorder(HFTree *T,int index);
相关函数:
#include "Haffman_tree.h"
void main()
{
int weight[4] = {1,2,3,4};
HFTree *T = InitTree(weight,4);
CreatHF_tree(T);
Preorder(T,T->length - 1);
printf("\n");
system("pause");
return ;
}
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[i].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[i].weight;
secondIndex = i;
}
}
}
int *res = (int *)malloc(sizeof(int) * 2);
res[0] = minIndex;
res[1] = secondIndex;
return res;
}
void CreatHF_tree(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 Preorder(HFTree *T,int index)
{
if(index != -1)
{
printf("%d\t",T->data[index].weight);
Preorder(T,T->data[index].lchild);
Preorder(T,T->data[index].rchild);
}
}
测试结果:
声明:此文章为学习笔记,如有侵权请联系删除。