关于fw大学生使用书上和别人代码实现优先队列哈夫曼的事

CSDN上有很多关于实现哈夫曼树的博客,但是很少有优先队列的(由于书上用的优先队列所以想试试,网上的教程过于简单)但是书上没有main()函数导致不知道具体的实现。
这里我借鉴了Github上面的一个大佬,感觉他的代码写的非常清晰简洁,极具美感,推荐大家去康康。

哈夫曼树–Daipuwei

#include<iostream>
#include<queue>
#include<vector>
using namespace std;


class Hftree {
private:
	int val;
	char sym;
	Hftree* left;
	Hftree* right;
public:
	Hftree(int v, char s, Hftree *l, Hftree *r)
	{
		val = v;
		sym = s;
		left = l;
		right = r;
	}

	~Hftree()
	{

	}
	int weight()
	{
		return val;
	}
	void PreOrder(Hftree *r)
	{
		if (r)
		{
			cout << r->val << " " << r->sym << "\t";
			PreOrder(r->left);
			PreOrder(r->right);
		}
	}
};

class cmp {
public:
	bool operator()(Hftree*l, Hftree *r)
	{
		return l->weight() > r->weight();
	}
};

Hftree* CreateHftree(int v[], char s[], int n)
{
	priority_queue < Hftree*, vector<Hftree*>, cmp> Q;
	for (int i = 0; i < n; i++)
	{
		Hftree *r = new Hftree(v[i], s[i], NULL, NULL);
		Q.push(r);
	}
	while (Q.size() > 1)
	{
		Hftree *lc = Q.top();
		Q.pop();
		Hftree *rc = Q.top();
		Q.pop();
		Hftree *parent = new Hftree(lc->weight() + rc->weight(), 't', lc, rc);
		Q.push(parent);
	}
	return Q.top();
}

int main()
{
	Hftree *r;
	int n;
	cin >> n;
	int *v = new int[n + 1];
	char *s = new char[n + 1];
	for (int i = 0; i < n; i++)
	{
		cin >> s[i] >> v[i];
	}
	r = CreateHftree(v, s, n);
	r->PreOrder(r);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值