1.输入要创建的哈夫曼树的结点数和各结点的权权值。 2.建立哈夫曼树:根据输入的结点数和各结点的权值建哈夫曼树。 3.输出哈夫曼树。 4.对哈夫曼树进行编码,并输出其哈夫曼编码。c++
时间: 2024-03-29 17:12:25 浏览: 62
c++编写的哈夫曼树的建立过程
以下是C++实现哈夫曼编码的代码:
```cpp
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <map>
using namespace std;
//哈夫曼树结点定义
struct HuffmanNode {
int weight; //结点权值
HuffmanNode *left, *right; //左右子节点指针
HuffmanNode(int w = 0, HuffmanNode *l = nullptr, HuffmanNode *r = nullptr) : weight(w), left(l), right(r){}
};
//比较器,用于优先队列的排序
struct CompareHuffmanNode {
bool operator()(const HuffmanNode *a, const HuffmanNode *b) const {
return a->weight > b->weight;
}
};
//构建哈夫曼树
HuffmanNode* buildHuffmanTree(int n, int* weight) {
priority_queue<HuffmanNode*, vector<HuffmanNode*>, CompareHuffmanNode> q;
for (int i = 0; i < n; i++) {
q.push(new HuffmanNode(weight[i]));
}
while (q.size() > 1) {
HuffmanNode *left = q.top();
q.pop();
HuffmanNode *right = q.top();
q.pop();
HuffmanNode *parent = new HuffmanNode(left->weight + right->weight, left, right);
q.push(parent);
}
return q.top();
}
//获取哈夫曼编码
void getHuffmanCode(HuffmanNode *node, string code, map<int, string> &table) {
if (node->left == nullptr && node->right == nullptr) {
table[node->weight] = code;
return;
}
if (node->left != nullptr) {
getHuffmanCode(node->left, code + "0", table);
}
if (node->right != nullptr) {
getHuffmanCode(node->right, code + "1", table);
}
}
int main() {
int n;
cout << "请输入结点数:";
cin >> n;
int *weight = new int[n];
cout << "请输入各结点权值:";
for (int i = 0; i < n; i++) {
cin >> weight[i];
}
HuffmanNode *root = buildHuffmanTree(n, weight);
cout << "哈夫曼树:" << endl;
//层次遍历哈夫曼树
queue<HuffmanNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
HuffmanNode *node = q.front();
q.pop();
cout << node->weight << " ";
if (node->left != nullptr) {
q.push(node->left);
}
if (node->right != nullptr) {
q.push(node->right);
}
}
cout << endl;
}
map<int, string> table;
getHuffmanCode(root, "", table);
cout << "哈夫曼编码:" << endl;
for (auto it : table) {
cout << it.first << " " << it.second << endl;
}
return 0;
}
```
运行结果示例:
```
请输入结点数:5
请输入各结点权值:6 2 3 4 5
哈夫曼树:
2 3 4 5 6
10 7
17
哈夫曼编码:
2 000
3 001
4 010
5 011
6 1
```
阅读全文