构造哈夫曼树,然后输出它树的中序序列。
给出词频(不超过10个,输入值不是有序输入),根据词频构造哈夫曼树。
为确保构建的哈夫曼树唯一,本题做如下限定:
(1)选择根结点权值最小的两棵二叉树时,选取权值较小者作为左子树。
(2)若多棵二叉树根结点权值相等,按先后次序分左右,先出现的作为左子树,后出现的作为右子树。
输入格式:
第一行输入词频个数; 第二行按从小到大的顺序输入每个词频
输出格式:
输出中序序列,中间以一个空格隔开
输入样例:
3
1 2 1
输出样例:
2 4 1 2 1
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <queue>
using namespace std;
typedef struct Haffm {
int data;
Haffm* lchild;
Haffm* rchild;
}Haffmtree;
struct myCompare {
bool operator()(Haffmtree*& a, Haffmtree*& b) {
return a->data > b->data;
}
};
Haffmtree* buildHaffmtree(priority_queue<Haffmtree*, vector<Haffmtree*>, myCompare>& haffm) {
if (haffm.empty()) {
exit(1);
}
do {
Haffmtree* first = haffm.top();
haffm.pop();
if (haffm.empty()) {
return first;
}
Haffmtree* root = new Haffmtree;
root->lchild = first;
root->rchild = haffm.top();
root->data = root->lchild->data + root->rchild->data;
haffm.pop();
haffm.push(root);
} while (!haffm.empty());
}
void InorderTraversal(Haffmtree*& root) {//前序遍历打印结果
if (!root) {
return;
}
InorderTraversal(root->lchild);
cout << root->data << " ";
InorderTraversal(root->rchild);
}
int main(void) {
priority_queue<Haffmtree*, vector<Haffmtree*>, myCompare> haffm;
int n;
cin >> n;
while (n--) {
Haffmtree* node = new Haffmtree;
cin >> node->data;
node->lchild = node->rchild = NULL;
haffm.push(node);
}
Haffmtree* root = buildHaffmtree(haffm);
InorderTraversal(root);
system("pause");
return 0;
}