构造哈夫曼树,然后输出它树的中序序列。
给出词频(不超过10个,输入值不是有序输入),根据词频构造哈夫曼树。
为确保构建的哈夫曼树唯一,本题做如下限定:
(1)选择根结点权值最小的两棵二叉树时,选取权值较小者作为左子树。
(2)若多棵二叉树根结点权值相等,按先后次序分左右,先出现的作为左子树,后出现的作为右子树。
输入格式:
第一行输入词频个数; 第二行按从小到大的顺序输入每个词频
输出格式:
输出中序序列,中间以一个空格隔开
输入样例:
3
1 2 1
输出样例:
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;
}