用c++实现哈夫曼树
时间: 2024-03-23 13:32:52 浏览: 72
以下是用C++实现哈夫曼树的代码示例:
```c++
#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->ch != '\0') {
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'};
HuffmanNode* root = buildHuffmanTree(weights, chars);
vector<string> codes(128);
generateHuffmanCode(root, "", codes);
for (int i = 0; i < 128; i++) {
if (!codes[i].empty()) {
cout << (char)i << ": " << codes[i] << endl;
}
}
return 0;
}
```
阅读全文