C++ 哈弗曼树类 创建哈弗曼树、输出哈弗曼树、输出哈弗曼编码

#include <stdlib.h>
#include <iostream>
int *findMin(struct TreeNode *trees,int length);
using namespace std;
struct huffmanCode{
	int *p;
	int start;
};
struct TreeNode{
	int wight;
	int parent;
	int lchild;
	int rchild;
}; 

class huffmanTree{
	public :
		struct TreeNode *array; 
		int start;
		int length;
		huffmanTree(int *array,int length);
		void print(int start);
		struct huffmanCode Code(int index); 
};

huffmanTree::huffmanTree(int *array,int length){
	//创建节点数组 初始化 
//	struct TreeNode trees[length*2-1];
	struct TreeNode *trees;
	trees=(struct TreeNode*)malloc((2*length-1)*sizeof(struct TreeNode));
	int *p;//权重最小两个节点下标 
	for(int i=0;i<length*2-1;i++){
		if(i<length){
			trees[i].wight=array[i];
		}
		trees[i].lchild=-1;
		trees[i].rchild=-1;
		trees[i].parent=-1;
	}
	//创建huffmanTree
	for(int i=0;i<length-1;i++){
		p=findMin(trees,length+i);
		trees[i+length].lchild=p[0];
		trees[i+length].rchild=p[1];
		trees[i+length].wight=trees[p[0]].wight+trees[p[1]].wight;
		trees[p[0]].parent=i+length;
		trees[p[1]].parent=i+length;
	}
	this->start=2*length-1; //数组长度 
	this->array=trees;
	this->length=length;
}
//输出哈弗曼树 树根应该是在下标为2*length-2处 
void huffmanTree::print(int start){
	cout<<this->array[start].wight<<" ";
	if(this->array[start].lchild!=-1){
		this->print(this->array[start].lchild);
	}
	if(this->array[start].rchild!=-1){
		this->print(this->array[start].rchild);
	}
}
//输出编码  参数是下标 
struct huffmanCode huffmanTree::Code(int index){
	struct huffmanCode code;
	struct TreeNode child=this->array[index];
	int parent=child.parent;
	code.start=this->length;
	code.p=(int *)malloc(length*sizeof(int));
	while(parent!=-1){
		if(this->array[parent].lchild==index){
			code.p[code.start]=0;
		}else{
			code.p[code.start]=1;
		}
		index=parent;
		code.start--;
		parent=this->array[parent].parent;		
	}
	for(int i=code.start+1;i<=length;i++){
		cout<<code.p[i];
	}
	return code;
}
int main(void){
	int array[5]={1,2,3,3,4};
	huffmanTree tree(array,5);
	tree.print(tree.start-1);
	tree.Code(1);
	return 0;
}
//查找两个最小值下标 
int *findMin(struct TreeNode *trees,int length){
	int min,min2;
	int x,x2;
	int *p;
	p=(int*)malloc(2*sizeof(int));
	//初始化起始值
	min=min2=10000;
	x=x2=0;
	//开始查找 
	for(int i=0;i<length;i++){
		if(trees[i].parent==-1){
			if(trees[i].wight<=min){
				min2=min;
				x2=x;
				min=trees[i].wight;
				x=i;
			}else if(trees[i].wight<min2){
				min2=trees[i].wight;
				x2=i;
			}
		}
	}
	p[0]=x;
	p[1]=x2;
	return p;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值