c++实现哈夫曼树的编码与解码
时间: 2023-07-09 11:08:01 浏览: 139
哈夫曼树是一种常用的数据结构,可以用于数据的压缩和解压缩。下面是C++实现的哈夫曼树编码和解码的示例代码:
```c++
#include <iostream>
#include <string>
#include <queue>
#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 Compare {
bool operator() (const TreeNode* a, const TreeNode* b) {
return a->freq > b->freq;
}
};
void buildHuffmanTree(string str, unordered_map<char, int>& freqMap, priority_queue<TreeNode*, vector<TreeNode*>, Compare>& minHeap) {
for (char c : str) {
if (freqMap.find(c) == freqMap.end()) {
freqMap[c] = 1;
} else {
freqMap[c]++;
}
}
for (auto& entry : freqMap) {
TreeNode* node = new TreeNode(entry.first, entry.second);
minHeap.push(node);
}
while (minHeap.size() > 1) {
TreeNode* left = minHeap.top(); minHeap.pop();
TreeNode* right = minHeap.top(); minHeap.pop();
TreeNode* parent = new TreeNode('$', left->freq + right->freq);
parent->left = left;
parent->right = right;
minHeap.push(parent);
}
}
void encode(TreeNode* node, string code, unordered_map<char, string>& codeMap) {
if (node == nullptr) return;
if (node->left == nullptr && node->right == nullptr) {
codeMap[node->ch] = code;
return;
}
encode(node->left, code + "0", codeMap);
encode(node->right, code + "1", codeMap);
}
void huffmanEncode(string str, unordered_map<char, string>& codeMap) {
unordered_map<char, int> freqMap;
priority_queue<TreeNode*, vector<TreeNode*>, Compare> minHeap;
buildHuffmanTree(str, freqMap, minHeap);
TreeNode* root = minHeap.top();
encode(root, "", codeMap);
}
void huffmanDecode(TreeNode* root, string code, string& result) {
if (root == nullptr) return;
TreeNode* curr = root;
for (char c : code) {
if (c == '0') {
curr = curr->left;
} else {
curr = curr->right;
}
if (curr->left == nullptr && curr->right == nullptr) {
result += curr->ch;
curr = root;
}
}
}
int main() {
string str = "hello world";
unordered_map<char, string> codeMap;
huffmanEncode(str, codeMap);
string encoded = "";
for (char c : str) {
encoded += codeMap[c];
}
cout << "Encoded string: " << encoded << endl;
string decoded = "";
TreeNode* root = new TreeNode('$', 0);
for (auto& entry : codeMap) {
string code = entry.second;
char ch = entry.first;
TreeNode* curr = root;
for (char c : code) {
if (c == '0') {
if (curr->left == nullptr) {
curr->left = new TreeNode('$', 0);
}
curr = curr->left;
} else {
if (curr->right == nullptr) {
curr->right = new TreeNode('$', 0);
}
curr = curr->right;
}
}
curr->ch = ch;
}
huffmanDecode(root, encoded, decoded);
cout << "Decoded string: " << decoded << endl;
return 0;
}
```
以上代码实现了哈夫曼树的编码和解码,其中`buildHuffmanTree`函数用于构建哈夫曼树,`encode`函数用于将哈夫曼树转换为编码表,`huffmanEncode`函数用于对字符串进行编码,`huffmanDecode`函数用于对编码后的字符串进行解码。
阅读全文