建立哈夫曼树,实现基于输入的字符及其权值求哈夫曼编码和进行编码解码的功能。要求:1.输出每个字符的哈夫曼编码。2.输入由上述若干字符组成的字符串,对电文进行编码并输出。3. 输入一串哈夫曼编码,进行解码并输出字符串。用C++写出代码
时间: 2023-07-19 10:06:35 浏览: 139
hfm.rar_哈夫曼_哈夫曼树的建立_哈夫曼编码_哈夫曼编码 译码
5星 · 资源好评率100%
以下是C++实现的代码:
```c++
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
// 哈夫曼树节点
struct HuffmanNode {
char ch; // 当前节点存储的字符
int freq; // 当前节点存储的字符的频率
HuffmanNode *left; // 左子节点指针
HuffmanNode *right; // 右子节点指针
HuffmanNode(char _ch, int _freq) : ch(_ch), freq(_freq), left(nullptr), right(nullptr) {}
};
// 哈夫曼树比较器
struct HuffmanComparator {
bool operator()(HuffmanNode *n1, HuffmanNode *n2) {
return n1->freq > n2->freq;
}
};
// 构造哈夫曼树
HuffmanNode *buildHuffmanTree(unordered_map<char, int> freqMap) {
priority_queue<HuffmanNode *, vector<HuffmanNode *>, HuffmanComparator> pq;
for (auto it : freqMap) {
pq.push(new HuffmanNode(it.first, it.second));
}
while (pq.size() > 1) {
auto left = pq.top();
pq.pop();
auto right = pq.top();
pq.pop();
auto parent = new HuffmanNode('\0', left->freq + right->freq);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// 哈夫曼编码
void huffmanEncode(HuffmanNode *root, string str, unordered_map<char, string> &codeMap) {
if (!root) {
return;
}
if (!root->left && !root->right) {
codeMap[root->ch] = str;
}
huffmanEncode(root->left, str + "0", codeMap);
huffmanEncode(root->right, str + "1", codeMap);
}
// 哈夫曼编码压缩
string huffmanCompress(string str, unordered_map<char, string> &codeMap) {
string compressed;
for (char c : str) {
compressed += codeMap[c];
}
return compressed;
}
// 哈夫曼解码
string huffmanDecode(HuffmanNode *root, string str) {
string decoded;
HuffmanNode *cur = root;
for (char c : str) {
if (c == '0') {
cur = cur->left;
} else {
cur = cur->right;
}
if (!cur->left && !cur->right) {
decoded += cur->ch;
cur = root;
}
}
return decoded;
}
int main() {
string str = "hello world";
unordered_map<char, int> freqMap;
for (char c : str) {
freqMap[c]++;
}
HuffmanNode *root = buildHuffmanTree(freqMap);
unordered_map<char, string> codeMap;
huffmanEncode(root, "", codeMap);
for (auto it : codeMap) {
cout << it.first << ": " << it.second << endl;
}
string compressed = huffmanCompress(str, codeMap);
cout << "compressed: " << compressed << endl;
string decoded = huffmanDecode(root, compressed);
cout << "decoded: " << decoded << endl;
return 0;
}
```
注意,本代码实现的哈夫曼编码和解码只支持ASCII字符集。如果需要支持更多字符集,需要对哈夫曼树节点的结构进行修改。
阅读全文