请帮我编写c++代码,要求如下,创建哈夫曼树,并实现对其编码,包括以下功能: 1.输入要创建的哈夫曼树的结点数和各结点的权权值。 2.建立哈夫曼树:根据输入的结点数和各结点的权值建哈夫曼树。 3.输出哈夫曼树。 4.对哈夫曼树进行编码,并输出其哈夫曼编码
时间: 2023-06-28 21:13:55 浏览: 136
哈弗曼树的建立及哈弗曼编码的生成 c++实现
5星 · 资源好评率100%
以下是一个简单的 C++ 实现:
```c++
#include <iostream>
#include <queue>
#include <string>
#include <unordered_map>
using namespace std;
struct HuffmanNode {
char ch;
int weight;
HuffmanNode *left, *right;
HuffmanNode(char c, int w) : ch(c), weight(w), left(nullptr), right(nullptr) {}
HuffmanNode(int w) : HuffmanNode('\0', w) {}
};
struct HuffmanCompare {
bool operator()(const HuffmanNode* a, const HuffmanNode* b) const {
return a->weight > b->weight;
}
};
void printHuffmanTree(HuffmanNode* root, string code = "") {
if (!root) return;
if (root->ch != '\0') cout << root->ch << ": " << code << endl;
printHuffmanTree(root->left, code + "0");
printHuffmanTree(root->right, code + "1");
}
void encodeHuffmanTree(HuffmanNode* root, string code, unordered_map<char, string>& encoding) {
if (!root) return;
if (root->ch != '\0') encoding[root->ch] = code;
encodeHuffmanTree(root->left, code + "0", encoding);
encodeHuffmanTree(root->right, code + "1", encoding);
}
HuffmanNode* buildHuffmanTree(int n, int w[]) {
priority_queue<HuffmanNode*, vector<HuffmanNode*>, HuffmanCompare> pq;
for (int i = 0; i < n; i++) {
HuffmanNode* node = new HuffmanNode(i, w[i]);
pq.push(node);
}
while (pq.size() > 1) {
HuffmanNode* left = pq.top();
pq.pop();
HuffmanNode* right = pq.top();
pq.pop();
HuffmanNode* parent = new HuffmanNode(left->weight + right->weight);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
int main() {
int n;
cout << "Enter the number of nodes: ";
cin >> n;
int w[n];
cout << "Enter the weight of each node: ";
for (int i = 0; i < n; i++) {
cin >> w[i];
}
HuffmanNode* root = buildHuffmanTree(n, w);
cout << "Huffman tree:" << endl;
printHuffmanTree(root);
unordered_map<char, string> encoding;
encodeHuffmanTree(root, "", encoding);
cout << "Huffman encoding:" << endl;
for (auto& e : encoding) {
cout << e.first << ": " << e.second << endl;
}
return 0;
}
```
该程序使用优先队列来构建哈夫曼树,并使用递归方式来打印哈夫曼树和编码。注意,该代码没有进行内存管理,可能会导致内存泄漏。在实际应用中,应该使用智能指针等技术来管理动态分配的内存。
阅读全文