//哈夫曼树
#include<stdio.h>
#include<stdlib.h>
typedef struct{
int weight;//权
int parent,lchild,rchild; //亲结点 左节点 右节点
}HTNode,*HuffmanTree;
typedef struct{
int weight;
int num;
int parent;
}Bijiao;//用于比较暂存的
//构造哈夫曼树
static int s1,s2;//保存最小树
HuffmanTree CreateHuffmanTree(int n){ //n个权结点
HuffmanTree HT;
if(n<=1) return NULL;
int m=2*n-1; //n个结点+(n-1)次合并成的n-1个新结点需要2n-1个存储空间
HT=(HuffmanTree)malloc(sizeof(HTNode)*(m+1));//为简便0号不用多定义一位
for(int i=1;i<=m;i++){
HT[i].lchild=HT[i].rchild=HT[i].parent=0;//动态数组HT
}
for(int i=1;i<=n;i++){ //录入n个权结点
scanf("%d",&HT[i].weight);
}
for(int i=n+1;i<=m;i++){ //合并产生n-1个结点放在后边
//选出两个最小的s1和s2
//为便利构造一个从小到大的HT信息数组Hcopy
Bijiao Hcopy[m+1],temp;//表会越来越大所以得和HT等长
int a,b;
for(int i=1;i<=m;i++){
Hcopy[i].weight=HT[i].weight;
Hcopy[i].parent=HT[i].parent;
Hcopy[i].num=i;
}
//给H_copy从小到大排序
for(int i=1;i<m;i++){
for(int j=i+1;j<=m;j++){
if(Hcopy[i].weight>Hcopy[j].weight){
temp=Hcopy[i];
Hcopy[i]=Hcopy[j];
Hcopy[j]=temp;
}
}
}
//只要新结点parent为0的结点的最小两个
a=1;
while(Hcopy[a].parent!=0){
a++;
}
s1=Hcopy[a].num;
b=a+1;
while(Hcopy[b].parent!=0){
b++;
}
s2=Hcopy[b].num;
HT[s1].parent=HT[s2].parent=i;//新结点是s1s2的父结点
HT[i].lchild=s1;HT[i].rchild=s2;//s1s2分别作为i的左右孩子
HT[i].weight=HT[s1].weight+HT[s2].weight;//权值为s1s2和
}
return HT;
}
int main(){
int n;
printf("输入结点数: ");
scanf("%d",&n);
HuffmanTree HT=CreateHuffmanTree(n);
printf("打印表:\n i\tweight\tparent\tlchild\trchild\n");
for(int i=1;i<=2*n-1;i++){
printf("%4d\t%4d\t%4d\t%4d\t%4d\n",i,HT[i].weight,HT[i].parent,HT[i].lchild,HT[i].rchild);
}
system("pause");
return 0;
}
哈夫曼树顺序存储
最新推荐文章于 2023-05-14 17:43:26 发布