哈夫曼编码c++递归实现

#include <iostream>
#include <queue>
#include<algorithm>
#include<string>
using namespace std;
	struct Node
	{
		char c;
		int val;
		Node *r=NULL;
		Node *l=NULL;
	};
	struct tmp  
	{
	int key;
	Node* node;
	bool operator < (const tmp &t) const
	{
		return key>t.key;
	}
	}temp;
	int print_Haffman(Node* node,string str);
	//需要修改的地方 
	int list_val[]={5,4,3,2,1};
	char list_char[]={'A','B','C','D','E'};
	int len=sizeof(list_val)/sizeof(list_val[0]); 
int main(int argc, char** argv) {
	Node list[len];
	for (int i=0;i<len;i++)
	{
		list[i].c=list_char[i];
		list[i].val=list_val[i];
	}
	priority_queue<tmp> que;//这个是优先队列,cpp泛值属实没搞懂 
	for (int i=0;i<len;i++)
	{
		temp.node=&list[i];
		temp.key=list[i].val;
		que.push(temp);
	}
	int i1=0;
	Node list1[len];
	while(que.size()!=1)
	{
		int val=0;
		Node *tmpNode=&list1[i1];
		tmpNode->l=que.top().node;
		que.pop();
		tmpNode->r=que.top().node;
		que.pop();
		tmpNode->val=tmpNode->r->val+tmpNode->l->val;
		temp.key=tmpNode->val;
		temp.node=tmpNode;
		que.push(temp);
		i1++;
	}
	
	print_Haffman(que.top().node,"");
	return 0;
}
int print_Haffman(Node* node,string str)
{
	if(!node->l)
	{
		cout<<node->c<<":"<<str<<endl;
		return 0;
	}
	print_Haffman(node->l,str+"0");
	print_Haffman(node->r,str+"1");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值