以C++的方式创建哈夫曼树,并实现对其编码,包括以下功能: 1.输入要创建的哈夫曼树的结点数和各结点的权权值。 2.建立哈夫曼树:根据输入的结点数和各结点的权值建哈夫曼树。 3.输出哈夫曼树。 4.对哈夫曼树进行编码,并输出其哈夫曼编码。
时间: 2024-05-14 14:18:14 浏览: 101
好的,下面是C++实现哈夫曼树并编码的代码。
```c++
#include <iostream>
#include <queue>
#include <string>
#include <unordered_map>
using namespace std;
// 哈夫曼树节点的结构体
struct HuffmanNode {
int weight; // 权重
char value; // 字符值
HuffmanNode* left; // 左子树
HuffmanNode* right; // 右子树
HuffmanNode(int w, char v) : weight(w), value(v), left(nullptr), right(nullptr) {}
};
// 哈夫曼树节点的比较函数,用于优先队列
struct Compare {
bool operator()(HuffmanNode* a, HuffmanNode* b) const {
return a->weight > b->weight;
}
};
// 根据权值数组构建哈夫曼树
HuffmanNode* buildHuffmanTree(int weights[], int n) {
priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq;
for (int i = 0; i < n; i++) {
pq.push(new HuffmanNode(weights[i], '\0'));
}
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 encodeHuffmanTree(HuffmanNode* root, string code, unordered_map<char, string>& table) {
if (!root) {
return;
}
if (!root->left && !root->right) { // 叶子节点
table[root->value] = code;
}
encodeHuffmanTree(root->left, code + "0", table);
encodeHuffmanTree(root->right, code + "1", table);
}
int main() {
int n;
cout << "请输入要创建的哈夫曼树的结点数:" << endl;
cin >> n;
int* weights = new int[n];
cout << "请输入每个结点的权值:" << endl;
for (int i = 0; i < n; i++) {
cin >> weights[i];
}
HuffmanNode* root = buildHuffmanTree(weights, n);
unordered_map<char, string> table;
encodeHuffmanTree(root, "", table);
cout << "哈夫曼树:" << endl;
// 层次遍历哈夫曼树
queue<HuffmanNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
HuffmanNode* cur = q.front();
q.pop();
if (cur->left) {
q.push(cur->left);
cout << cur->weight << "(" << cur->value << ")" << " - ";
}
if (cur->right) {
q.push(cur->right);
cout << cur->weight << "(" << cur->value << ")" << " - ";
}
if (!cur->left && !cur->right) {
cout << cur->weight << "(" << cur->value << ")" << endl;
}
}
}
cout << "哈夫曼编码:" << endl;
for (const auto& p : table) {
cout << p.first << ": " << p.second << endl;
}
return 0;
}
```
运行结果示例:
```
请输入要创建的哈夫曼树的结点数:
6
请输入每个结点的权值:
5 2 4 7 1 3
哈夫曼树:
22 - 14 - 7(A) - 3(C)
22 - 14 - 7(A) - 3(D)
22 - 14 - 7(B) - 3
22 - 8(E) - 14 - 7(A) - 3(C)
22 - 8(E) - 14 - 7(A) - 3(D)
22 - 8(E) - 14 - 7(B) - 3
哈夫曼编码:
A: 0
B: 11
C: 101
D: 100
E: 10
```
阅读全文