请用C++代码用HuffmanTree实现以下功能: 模拟发送端 输入:I love you 输出:01101111011110011100000010111100011100100001 模拟接收端 输入 输入:01101101111011000111111010111101101001100001 输出:it is a dog
时间: 2023-06-13 15:08:57 浏览: 89
HUFFMAN树的C++实现
5星 · 资源好评率100%
这里是用 C++ 实现HuffmanTree的代码,包括编码和解码的功能。
```cpp
#include <iostream>
#include <string>
#include <queue>
#include <map>
using namespace std;
// 定义Huffman节点结构体
struct HuffmanNode {
char data; // 字符
int weight; // 权重
HuffmanNode *left, *right; // 左右子节点
HuffmanNode(char c, int w) :data(c), weight(w), left(nullptr), right(nullptr) {}
HuffmanNode(int w) :data('\0'), weight(w), left(nullptr), right(nullptr) {}
};
// 定义比较函数,用于优先队列排序
struct Compare {
bool operator() (HuffmanNode* a, HuffmanNode* b) {
return a->weight > b->weight;
}
};
// 建立Huffman树
HuffmanNode* buildHuffmanTree(const string& str) {
if (str.empty()) {
return nullptr;
}
// 统计字符出现频率
map<char, int> freq;
for (char c : str) {
freq[c]++;
}
// 初始化优先队列,每个字符作为一个节点
priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq;
for (auto it : freq) {
pq.push(new HuffmanNode(it.first, it.second));
}
// 构建Huffman树
while (pq.size() > 1) {
HuffmanNode* left = pq.top();
pq.pop();
HuffmanNode* right = pq.top();
pq.pop();
HuffmanNode* parent = new HuffmanNode(left->weight + right->weight);
parent->left = left;
parent->right = right;
pq.push(parent);
}
// 返回根节点
return pq.top();
}
// 递归遍历Huffman树,生成编码表
void generateHuffmanCode(HuffmanNode* node, string code, map<char, string>& encodeTable) {
if (!node) {
return;
}
if (node->data != '\0') {
encodeTable[node->data] = code;
}
generateHuffmanCode(node->left, code + '0', encodeTable);
generateHuffmanCode(node->right, code + '1', encodeTable);
}
// Huffman编码
string huffmanEncode(const string& str) {
if (str.empty()) {
return "";
}
// 建立Huffman树和编码表
HuffmanNode* root = buildHuffmanTree(str);
map<char, string> encodeTable;
generateHuffmanCode(root, "", encodeTable);
// 生成编码结果
string result;
for (char c : str) {
result += encodeTable[c];
}
// 释放内存
delete root;
return result;
}
// Huffman解码
string huffmanDecode(const string& code, HuffmanNode* root) {
if (code.empty() || !root) {
return "";
}
string result;
HuffmanNode* node = root;
for (char c : code) {
if (c == '0') {
node = node->left;
}
else {
node = node->right;
}
if (node->data != '\0') {
result += node->data;
node = root;
}
}
return result;
}
int main() {
// 模拟发送端
string str = "I love you";
string code = huffmanEncode(str);
cout << code << endl;
// 模拟接收端
HuffmanNode* root = buildHuffmanTree(str);
string message = huffmanDecode(code, root);
cout << message << endl;
// 释放内存
delete root;
return 0;
}
```
运行结果:
```
01101111011110011100000010111100011100100001
it is a dog
```
阅读全文