huffman树c++
时间: 2023-11-30 12:42:35 浏览: 77
哈夫曼树(C++)
5星 · 资源好评率100%
以下是C++实现Huffman树的代码示例:
```cpp
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// 定义哈夫曼树节点
struct HuffmanNode {
int weight; // 权值
char ch; // 字符
HuffmanNode *left, *right; // 左右子节点
HuffmanNode(int w, char c) : weight(w), ch(c), left(nullptr), right(nullptr) {}
};
// 定义比较函数,用于优先队列
struct cmp {
bool operator()(HuffmanNode* a, HuffmanNode* b) {
return a->weight > b->weight;
}
};
// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(vector<int>& weights, vector<char>& chars) {
priority_queue<HuffmanNode*, vector<HuffmanNode*>, cmp> pq;
for (int i = 0; i < weights.size(); i++) {
pq.push(new HuffmanNode(weights[i], chars[i]));
}
while (pq.size() > 1) {
HuffmanNode* left = pq.top();
pq.pop();
HuffmanNode* right = pq.top(); pq.pop();
HuffmanNode* parent = new HuffmanNode(left->weight + right->weight, '\0');
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// 遍历哈夫曼树,生成哈夫曼编码
void generateHuffmanCode(HuffmanNode* root, string code, vector<string>& codes) {
if (!root) {
return;
}
if (!root->left && !root->right) {
codes[root->ch] = code;
}
generateHuffmanCode(root->left, code + "0", codes);
generateHuffmanCode(root->right, code + "1", codes);
}
int main() {
vector<int> weights = {5, 9, 12, 13, 16, 45};
vector<char> chars = {'a', 'b', 'c', 'd', 'e', 'f'};
vector<string> codes(128, "");
HuffmanNode* root = buildHuffmanTree(weights, chars);
generateHuffmanCode(root, "", codes);
for (int i = 0; i < 128; i++) {
if (codes[i] != "") {
cout << (char)i << ": " << codes[i] << endl;
}
}
return 0;
}
```
阅读全文