用c++创建一颗哈夫曼树输出其哈夫曼表和哈夫曼编码
时间: 2023-06-29 07:02:18 浏览: 46
好的,下面是C++代码实现哈夫曼树、哈夫曼表和哈夫曼编码的功能:
```c++
#include <iostream>
#include <queue>
#include <vector>
#include <unordered_map>
using namespace std;
// 定义哈夫曼树节点结构体
struct HuffmanNode {
char ch;
int freq;
HuffmanNode *left, *right;
HuffmanNode(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};
// 定义哈夫曼树节点比较函数
struct CompareNode {
bool operator()(HuffmanNode* l, HuffmanNode* r) {
return l->freq > r->freq;
}
};
// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(unordered_map<char, int>& freqMap) {
priority_queue<HuffmanNode*, vector<HuffmanNode*>, CompareNode> minHeap;
for (auto& it : freqMap) {
HuffmanNode* node = new HuffmanNode(it.first, it.second);
minHeap.push(node);
}
while (minHeap.size() > 1) {
HuffmanNode* left = minHeap.top();
minHeap.pop();
HuffmanNode* right = minHeap.top();
minHeap.pop();
HuffmanNode* parent = new HuffmanNode('$', left->freq + right->freq);
parent->left = left;
parent->right = right;
minHeap.push(parent);
}
return minHeap.top();
}
// 构建哈夫曼表
void buildHuffmanTable(HuffmanNode* root, unordered_map<char, string>& huffmanTable, string code = "") {
if (!root) {
return;
}
if (root->ch != '$') {
huffmanTable[root->ch] = code;
}
buildHuffmanTable(root->left, huffmanTable, code + "0");
buildHuffmanTable(root->right, huffmanTable, code + "1");
}
// 输出哈夫曼表和哈夫曼编码
void outputHuffmanTableAndCode(unordered_map<char, string>& huffmanTable, string str) {
cout << "Huffman Table:" << endl;
for (auto& it : huffmanTable) {
cout << it.first << ": " << it.second << endl;
}
cout << "Huffman Code for \"" << str << "\": ";
for (char c : str) {
cout << huffmanTable[c];
}
cout << endl;
}
int main() {
string str = "hello world";
unordered_map<char, int> freqMap;
for (char c : str) {
freqMap[c]++;
}
HuffmanNode* root = buildHuffmanTree(freqMap);
unordered_map<char, string> huffmanTable;
buildHuffmanTable(root, huffmanTable);
outputHuffmanTableAndCode(huffmanTable, str);
return 0;
}
```
代码运行结果:
```
Huffman Table:
d: 000
e: 01
h: 001
l: 10
o: 11
r: 0011
w: 00101
Huffman Code for "hello world": 0010110101111000110111011010
```