哈夫曼编码用c++实现
时间: 2023-11-24 11:50:41 浏览: 103
以下是C++实现哈夫曼编码的示例代码:
```c++
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
// 定义哈夫曼树节点
struct TreeNode {
char ch;
int freq;
TreeNode* left;
TreeNode* right;
TreeNode(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};
// 定义比较函数,用于优先队列
struct cmp {
bool operator()(TreeNode* a, TreeNode* b) {
return a->freq > b->freq;
}
};
// 构建哈夫曼树
TreeNode* buildHuffmanTree(unordered_map<char, int>& freqMap) {
priority_queue<TreeNode*, vector<TreeNode*>, cmp> pq;
for (auto& p : freqMap) {
pq.push(new TreeNode(p.first, p.second));
}
while (pq.size() > 1) {
TreeNode* left = pq.top();
pq.pop();
TreeNode* right = pq.top();
pq.pop();
TreeNode* parent = new TreeNode('#', left->freq + right->freq);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// 递归生成哈夫曼编码
void generateHuffmanCode(TreeNode* root, string code, unordered_map<char, string>& codeMap) {
if (!root) {
return;
}
if (!root->left && !root->right) {
codeMap[root->ch] = code;
}
generateHuffmanCode(root->left, code + "0", codeMap);
generateHuffmanCode(root->right, code + "1", codeMap);
}
// 哈夫曼编码
string huffmanEncoding(string s) {
unordered_map<char, int> freqMap;
for (char c : s) {
freqMap[c]++;
}
TreeNode* root = buildHuffmanTree(freqMap);
unordered_map<char, string> codeMap;
generateHuffmanCode(root, "", codeMap);
string res = ""; for (char c : s) {
res += codeMap[c];
}
return res;
}
// 哈夫曼解码
string huffmanDecoding(string s, TreeNode* root) {
string res = "";
TreeNode* cur = root;
for (char c : s) {
if (c == '0') {
cur = cur->left;
} else {
cur = cur->right;
}
if (!cur->left && !cur->right) {
res += cur->ch;
cur = root;
}
}
return res;
}
int main() {
string s = "hello world";
string encoded = huffmanEncoding(s);
cout << "Encoded string: " << encoded << endl;
TreeNode* root = buildHuffmanTree(unordered_map<char, int>());
string decoded = huffmanDecoding(encoded, root);
cout << "Decoded string: " << decoded << endl;
return 0;
}
```
阅读全文