#include <bits/stdc++.h>
using namespace std;
/*
哈夫曼编码
*/
struct node {
char c;//节点的权值
int value;//权值
node* l, * r;
node(char c,int f):c(c),value(f),l(NULL),r(NULL){}
};
// 自定义比较器,用于优先队列
struct Compare {
bool operator()(node* l, node* r) {
return l->value > r->value; // 频率小的优先级高
}
};
node* build_tree(map<char, int>& h) {
// 创建一个优先队列来存储森林中的节点
priority_queue<node*, vector<node*>, Compare> pq;
// 初始化森林,每个字符对应一个节点
for (auto pair : h) {
pq.push(new node(pair.first, pair.second));
}
// 迭代合并节点直到只剩一棵树
while (pq.size() > 1) {
node* left = pq.top(); pq.pop();
node* right = pq.top(); pq.pop();
// 创建一个新的内部节点
node* parent = new node('\0', left->value + right->value);
parent->l = left;
parent->r = right;
pq.push(parent);
}
// 最终队列中剩下的唯一节点即为哈夫曼树的根节点
return pq.top();
}
// 打印哈夫曼编码 (前序遍历)
void printHuffmanCodes(node* root, string str) {
if (!root) return;
// 如果是叶子节点,输出字符和对应的哈夫曼编码
if (root->c != '\0') {
cout << root->c << ": " << str << endl;
}
printHuffmanCodes(root->l, str + "0");
printHuffmanCodes(root->r, str + "1");
}
int main() {
map<char, int> freqMap = {
{'a', 5}, {'b', 9}, {'c', 12}, {'d', 13}, {'e', 16}, {'f', 45}
};
node* root = build_tree(freqMap);
return 0;
}
哈夫曼编码模板
最新推荐文章于 2024-08-09 22:34:59 发布