pta 构造哈夫曼树-有序输入 优先队列做法
构造哈夫曼树,然后输出它树的中序序列。
从小到大的顺序给出词频(不超过10个),根据词频构造哈夫曼树。
为确保构建的哈夫曼树唯一,本题做如下限定:
(1)选择根结点权值最小的两棵二叉树时,选取权值较小者作为左子树。
(2)若多棵二叉树根结点权值相等,按先后次序分左右,先出现的作为左子树,后出现的作为右子树。
输入格式:
第一行输入词频个数; 第二行按从小到大的顺序输入每个词频。
输出格式:
输出中序序列,中间以一个空格隔开。
输入样例:
3
1 1 2
输出样例:
2 4 1 2 1
思路:
1. 建立一个元素是二叉树结点的优先队列,要求权重小的在前。
2. 将输入的元素入队列。
3. 反复取出前两个结点,组成新结点,然后入队列,直到队列为空。此时队列的最后一个结点就是哈夫曼二叉树的根结点。
4. 中序遍历二叉树。
其中1 2 3步是用优先队列创造哈夫曼二叉树的步骤,还是比较重要的。
完整代码:
#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;
}