哈夫曼树编码译码代码cpp
时间: 2023-11-12 13:59:57 浏览: 165
哈夫曼编码译码_
以下是哈夫曼树编码译码的C++代码示例:
```c++
#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <map>
using namespace std;
// 哈夫曼树节点
struct HuffmanNode {
char ch;
int freq;
HuffmanNode *left, *right;
HuffmanNode(char c, int f) {
ch = c;
freq = f;
left = right = nullptr;
}
~HuffmanNode() {
delete left;
delete right;
}
};
// 比较函数
struct Compare {
bool operator()(const HuffmanNode* a, const HuffmanNode* b) const {
return a->freq > b->freq;
}
};
// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(map<char, int> freqMap) {
priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq;
for (auto& p : freqMap) {
pq.push(new HuffmanNode(p.first, p.second));
}
while (pq.size() > 1) {
HuffmanNode *left = pq.top(); pq.pop();
HuffmanNode *right = pq.top(); pq.pop();
HuffmanNode *parent = new HuffmanNode('$', left->freq + right->freq);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// 构建编码表
void buildCodeTable(HuffmanNode* root, string code, map<char, string>& codeTable) {
if (root == nullptr) {
return;
}
if (root->ch != '$') {
codeTable[root->ch] = code;
}
buildCodeTable(root->left, code + "0", codeTable);
buildCodeTable(root->right, code + "1", codeTable);
}
// 编码字符串
string encodeString(string str, map<char, string> codeTable) {
string encodedString = "";
for (char c : str) {
encodedString += codeTable[c];
}
return encodedString;
}
// 译码字符串
string decodeString(string str, HuffmanNode* root) {
string decodedString = "";
HuffmanNode* cur = root;
for (char c : str) {
if (c == '0') {
cur = cur->left;
} else {
cur = cur->right;
}
if (cur->ch != '$') {
decodedString += cur->ch;
cur = root;
}
}
return decodedString;
}
int main() {
// 统计频率
string str = "hello, world!";
map<char, int> freqMap;
for (char c : str) {
freqMap[c]++;
}
// 构建哈夫曼树
HuffmanNode* root = buildHuffmanTree(freqMap);
// 构建编码表
map<char, string> codeTable;
buildCodeTable(root, "", codeTable);
// 编码字符串
string encodedString = encodeString(str, codeTable);
cout << "Encoded string: " << encodedString << endl;
// 译码字符串
string decodedString = decodeString(encodedString, root);
cout << "Decoded string: " << decodedString << endl;
// 释放资源
delete root;
return 0;
}
```
该程序的输入为一个字符串,输出为该字符串的哈夫曼编码和译码结果。程序首先统计输入字符串中每个字符出现的频率,并利用此信息构建哈夫曼树。然后,程序根据哈夫曼树构建编码表,用于将输入字符串编码为哈夫曼编码。最后,程序将哈夫曼编码译码为原始字符串。
阅读全文