#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Treenode{
int weight;
int parent;
int lchild;
int rchild;
}treenode;
typedef struct HFtree{
struct Treenode*data;
int length;
}hftree;
//哈夫曼树的初始化
hftree* init(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 min1=100000;
int min2=100000;
int index1;
int index2;
for(int i=0;i<T->length;i++){
if(T->data[i].parent==0){
if(T->data[i].weight<min1){
min1=T->data[i].weight;
index1=i;
}
}
}
for(int i=0;i<T->length;i++){
if(T->data[i].parent==0&&i!=index1){
if(T->data[i].weight<min2){
min2=T->data[i].weight;
index2=i;
}
}
}
int *res=(int*)malloc(sizeof(int)*2);
res[0]=index1;
res[1]=index2;
return res;
}
void createhftree(hftree*T){
int *res;
int index1;
int index2;
int length=2 * T->length - 1;
for(int i=T->length;i<length;i++){
res=selectmin(T);
index1=res[0];
index2=res[1];
T->data[i].weight=T->data[index1].weight+T->data[index2].weight;
T->data[i].parent=0;
T->data[i].lchild=index1;
T->data[i].rchild=index2;
T->data[index1].parent=i;
T->data[index2].parent=i;
T->length++;
free(res);
}
}
void preorder(hftree*T,int index){
if(index!=-1){
printf("%d ",T->data[index].weight);
preorder(T,T->data[index].lchild);
preorder(T,T->data[index].rchild);
}
}
int main(){
int weight[4]={1,2,3,4};
hftree*T=init(weight,4);
createhftree(T);
preorder(T,T->length-1);
return 0;
}
哈夫曼树的实现(C语言)
最新推荐文章于 2024-08-30 18:33:22 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)