哈夫曼树顺序存储

//哈夫曼树
#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;
}
  

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值