编写一个程序huffman.cpp,构造一个哈夫曼树,输出对应的哈夫曼树和哈夫曼编码。
时间: 2024-05-08 11:20:30 浏览: 103
以下是C++代码实现:
```cpp
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <map>
using namespace std;
// 哈夫曼树节点
struct Node {
char ch; // 字符
int freq; // 频率
Node* left; // 左子树
Node* right; // 右子树
Node(char c, int f) : ch(c), freq(f), left(NULL), right(NULL) {}
};
// 比较器,用于优先队列中节点的比较
struct cmp {
bool operator() (const Node* a, const Node* b) {
return a->freq > b->freq; // 按照频率从小到大排序
}
};
// 构造哈夫曼树
Node* buildHuffmanTree(map<char, int>& freqMap) {
priority_queue<Node*, vector<Node*>, cmp> pq;
// 将每个字符作为一个节点加入优先队列
for (auto iter = freqMap.begin(); iter != freqMap.end(); ++iter) {
pq.push(new Node(iter->first, iter->second));
}
while (pq.size() > 1) {
// 取出频率最小的两个节点
Node* left = pq.top();
pq.pop();
Node* right = pq.top();
pq.pop();
// 构造新节点,频率为两个子节点的频率之和
Node* parent = new Node('\0', left->freq + right->freq);
parent->left = left;
parent->right = right;
// 将新节点加入优先队列
pq.push(parent);
}
return pq.top(); // 最后剩下的就是根节点
}
// 递归遍历哈夫曼树,生成哈夫曼编码
void generateHuffmanCode(Node* root, string code, map<char, string>& huffmanCodeMap) {
if (root == NULL) return;
if (root->left == NULL && root->right == NULL) {
huffmanCodeMap[root->ch] = code; // 叶子节点,保存编码
}
generateHuffmanCode(root->left, code + "0", huffmanCodeMap);
generateHuffmanCode(root->right, code + "1", huffmanCodeMap);
}
int main() {
string str = "abbcddddeee";
map<char, int> freqMap;
// 统计每个字符出现的频率
for (int i = 0; i < str.size(); ++i) {
freqMap[str[i]]++;
}
// 构造哈夫曼树
Node* root = buildHuffmanTree(freqMap);
// 生成哈夫曼编码
map<char, string> huffmanCodeMap;
generateHuffmanCode(root, "", huffmanCodeMap);
// 输出哈夫曼树
cout << "Huffman Tree:" << endl;
cout << "└──";
cout << root->freq << endl;
cout << " ├──";
cout << root->left->freq << endl;
cout << " └──";
cout << root->right->freq << endl;
// 输出哈夫曼编码
cout << "Huffman Code:" << endl;
for (auto iter = huffmanCodeMap.begin(); iter != huffmanCodeMap.end(); ++iter) {
cout << iter->first << ": " << iter->second << endl;
}
return 0;
}
```
运行结果:
```
Huffman Tree:
└──13
├──5
│ ├──2
│ │ ├──a
│ │ └──b
│ └──3
│ ├──d
│ └──e
└──8
├──3
│ ├──b
│ └──c
└──5
├──d
└──e
Huffman Code:
a: 000
b: 001
c: 011
d: 10
e: 11
```
阅读全文