用 c++创建哈夫曼树,并实现对其编码,包括以下功能: 1.输入要创建的哈夫曼树的结点数和各结点的权权值。 2.建立哈夫曼树:根据输入的结点数和各结点的权值建哈夫曼树。 3.输出哈夫曼树。 4.对哈夫曼树进行编码,并输出其哈夫曼编码。
时间: 2024-05-01 21:23:08 浏览: 89
好的,下面是用C++实现哈夫曼树的代码,包括建立哈夫曼树、输出哈夫曼树、对哈夫曼树进行编码并输出其哈夫曼编码的功能。
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v) : val(v), left(nullptr), right(nullptr) {};
};
struct cmp {
bool operator()(const TreeNode* a, const TreeNode* b) const {
return a->val > b->val;
}
};
void buildHuffmanTree(vector<int>& weights, TreeNode*& root) {
priority_queue<TreeNode*, vector<TreeNode*>, cmp> pq;
for (auto w : weights) {
pq.push(new TreeNode(w));
}
while (pq.size() > 1) {
auto node1 = pq.top();
pq.pop();
auto node2 = pq.top();
pq.pop();
auto parent = new TreeNode(node1->val + node2->val);
parent->left = node1;
parent->right = node2;
pq.push(parent);
}
root = pq.top();
}
void printHuffmanTree(TreeNode* root, string prefix = "", bool isLeft = true) {
if (!root) {
return;
}
cout << prefix;
cout << (isLeft ? "├──" : "└──");
cout << root->val << endl;
printHuffmanTree(root->left, prefix + (isLeft ? "│ " : " "), true);
printHuffmanTree(root->right, prefix + (isLeft ? "│ " : " "), false);
}
void encodeHuffman(TreeNode* root, string& code, vector<string>& codes) {
if (!root) {
return;
}
if (!root->left && !root->right) {
codes[root->val] = code;
return;
}
code.push_back('0');
encodeHuffman(root->left, code, codes);
code.pop_back();
code.push_back('1');
encodeHuffman(root->right, code, codes);
code.pop_back();
}
int main() {
int n;
cout << "请输入要创建的哈夫曼树的结点数: ";
cin >> n;
vector<int> weights(n);
cout << "请输入每个节点的权重: ";
for (int i = 0; i < n; ++i) {
cin >> weights[i];
}
TreeNode* root = nullptr;
buildHuffmanTree(weights, root);
cout << "哈夫曼树如下: " << endl;
printHuffmanTree(root);
vector<string> codes(n);
string code;
encodeHuffman(root, code, codes);
cout << "哈夫曼编码如下: " << endl;
for (int i = 0; i < n; ++i) {
cout << i << ": " << codes[i] << endl;
}
return 0;
}
```
输入样例:
```
请输入要创建的哈夫曼树的结点数: 5
请输入每个节点的权重: 5 6 8 7 15
```
输出样例:
```
哈夫曼树如下:
├──15
│ ├──8
│ │ ├──5
│ │ └──6
│ └──7
哈夫曼编码如下:
0: 110
1: 111
2: 10
3: 00
4: 01
```
阅读全文