怎么编写哈夫曼树作为头文件
时间: 2023-05-31 20:04:23 浏览: 110
以下是一个简单的哈夫曼树头文件的示例:
```c++
#ifndef HUFFMAN_TREE_H
#define HUFFMAN_TREE_H
#include <iostream>
#include <queue>
#include <unordered_map>
class HuffmanNode {
public:
char c;
int freq;
HuffmanNode* left;
HuffmanNode* right;
HuffmanNode(char c, int freq) {
this->c = c;
this->freq = freq;
left = nullptr;
right = nullptr;
}
bool is_leaf() {
return (left == nullptr && right == nullptr);
}
static bool compare(HuffmanNode* a, HuffmanNode* b) {
return a->freq > b->freq;
}
};
class HuffmanTree {
public:
HuffmanNode* root;
HuffmanTree(std::unordered_map<char, int>& freq_map) {
std::priority_queue<HuffmanNode*, std::vector<HuffmanNode*>, decltype(&HuffmanNode::compare)> pq(&HuffmanNode::compare);
for (auto& p : freq_map) {
pq.push(new HuffmanNode(p.first, p.second));
}
while (pq.size() > 1) {
auto a = pq.top(); pq.pop();
auto b = pq.top(); pq.pop();
auto c = new HuffmanNode('\0', a->freq + b->freq);
c->left = a;
c->right = b;
pq.push(c);
}
root = pq.top();
}
void encode(std::string& s, std::unordered_map<char, std::string>& encoding_map) {
std::string code;
encode_helper(root, code, encoding_map);
std::string encoded;
for (char c : s) {
encoded += encoding_map[c];
}
s = encoded;
}
void decode(std::string& s) {
std::string decoded;
auto node = root;
for (char c : s) {
if (c == '0') {
node = node->left;
} else {
node = node->right;
}
if (node->is_leaf()) {
decoded += node->c;
node = root;
}
}
s = decoded;
}
private:
void encode_helper(HuffmanNode* node, std::string& code, std::unordered_map<char, std::string>& encoding_map) {
if (node->is_leaf()) {
encoding_map[node->c] = code;
return;
}
code.push_back('0');
encode_helper(node->left, code, encoding_map);
code.pop_back();
code.push_back('1');
encode_helper(node->right, code, encoding_map);
code.pop_back();
}
};
#endif // HUFFMAN_TREE_H
```
该头文件包含两个类:`HuffmanNode` 和 `HuffmanTree`。
`HuffmanNode` 表示哈夫曼树中的一个节点,包含字符、频率以及左右子节点。
`HuffmanTree` 表示哈夫曼树,包含根节点以及编码和解码方法。
在 `HuffmanTree` 的构造函数中,使用优先队列来构建哈夫曼树。在编码和解码方法中,使用递归来遍历整个哈夫曼树,生成编码表和解码字符串。
阅读全文