7-11 构造哈夫曼树-有序输入

构造哈夫曼树,然后输出它树的中序序列。

从小到大的顺序给出词频(不超过10个),根据词频构造哈夫曼树。

为确保构建的哈夫曼树唯一,本题做如下限定:

(1)选择根结点权值最小的两棵二叉树时,选取权值较小者作为左子树。

(2)若多棵二叉树根结点权值相等,按先后次序分左右,先出现的作为左子树,后出现的作为右子树。

输入格式:

第一行输入词频个数;
第二行按从小到大的顺序输入每个词频

输出格式:

输出中序序列,中间以一个空格隔开

输入样例:

3
1 1 2

输出样例:

2 4 1 2 1 

代码示例如下:

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

typedef struct Haffm {
	int priority;//权重
	Haffm* lchild;
	Haffm* rchild;
}Haffmtree;

void midorder(Haffmtree*& root) {//中序遍历打印结果
	if (root==NULL)
		return;
	midorder(root->lchild);
	cout << root->priority <<" ";
	midorder(root->rchild);
}
struct myCompare {//比较函数,小的在前
	bool operator()(Haffmtree*& a, Haffmtree*& b) {
		return a->priority > b->priority;
	}
};

Haffmtree* buildHaffmtree(priority_queue<Haffmtree*, vector<Haffmtree*>, myCompare>& haffm) 
{
	do {
		Haffmtree* first = haffm.top();
		haffm.pop();
		if (haffm.empty()) {
			return first;
		}//哈夫曼数已经完成排序,first是根结点
		Haffmtree* root = new Haffmtree;
		root->lchild = first;
		root->rchild = haffm.top();
		haffm.pop();
		root->priority = root->lchild->priority + root->rchild->priority;
		//根结点权重是左右子树权重之和。
		haffm.push(root);//将根结点入队列
	} while (!haffm.empty());
}
int main() {
	priority_queue<Haffmtree*, vector<Haffmtree*>, myCompare> haffm;
	int n;
	cin >> n;
	while (n--) {
		Haffmtree* node = new Haffmtree;
		cin >> node->priority;
		node->lchild = node->rchild = nullptr;
		haffm.push(node);
	}
	Haffmtree* root = buildHaffmtree(haffm);
	midorder(root);
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_我想睡觉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值