C++字符集合S={A,B,C,D,E,F},权值集合(每个字符的出现次数)为W={2,5,8,9,12,16}请写一个程序,对字符集合根据对应权值集合进行哈夫曼编码,并输出该哈夫曼树的前中后序遍历和层次遍历序列
时间: 2023-08-21 08:02:37 浏览: 292
以下是C++代码实现:
```c++
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
struct Node {
char ch; // 字符
int freq; // 权值
Node *left, *right; // 左右子节点
Node(char c, int f) {
ch = c;
freq = f;
left = right = nullptr;
}
Node(int f, Node* l, Node* r) {
ch = '\0';
freq = f;
left = l;
right = r;
}
// 比较函数,用于优先队列
bool operator<(const Node &n) const {
return freq > n.freq;
}
};
// 哈夫曼编码
void huffmanCode(Node* root, string code, vector<string>& res) {
if (root == nullptr) return;
if (root->ch != '\0') res[root->ch - 'A'] = code;
huffmanCode(root->left, code + '0', res);
huffmanCode(root->right, code + '1', res);
}
int main() {
vector<char> chars = {'A', 'B', 'C', 'D', 'E', 'F'};
vector<int> freqs = {2, 5, 8, 9, 12, 16};
// 构建哈夫曼树
priority_queue<Node> pq;
for (int i = 0; i < chars.size(); i++) {
pq.push(Node(chars[i], freqs[i]));
}
while (pq.size() > 1) {
Node* left = new Node(pq.top().ch, pq.top().freq);
pq.pop();
Node* right = new Node(pq.top().ch, pq.top().freq);
pq.pop();
Node* parent = new Node(left->freq + right->freq, left, right);
pq.push(*parent);
}
// 输出前中后序遍历和层次遍历序列
vector<string> res(chars.size(), "");
Node* root = new Node(pq.top().freq, pq.top().left, pq.top().right);
huffmanCode(root, "", res);
cout << "前序遍历:";
function<void(Node*)> preOrder = [&](Node* node) {
if (node == nullptr) return;
cout << node->ch << " ";
preOrder(node->left);
preOrder(node->right);
};
preOrder(root);
cout << endl;
cout << "中序遍历:";
function<void(Node*)> inOrder = [&](Node* node) {
if (node == nullptr) return;
inOrder(node->left);
cout << node->ch << " ";
inOrder(node->right);
};
inOrder(root);
cout << endl;
cout << "后序遍历:";
function<void(Node*)> postOrder = [&](Node* node) {
if (node == nullptr) return;
postOrder(node->left);
postOrder(node->right);
cout << node->ch << " ";
};
postOrder(root);
cout << endl;
cout << "层次遍历:";
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* node = q.front();
q.pop();
cout << node->ch << " ";
if (node->left != nullptr) q.push(node->left);
if (node->right != nullptr) q.push(node->right);
}
cout << endl;
// 输出哈夫曼编码
cout << "哈夫曼编码:" << endl;
for (int i = 0; i < res.size(); i++) {
cout << chars[i] << ": " << res[i] << endl;
}
return 0;
}
```
输出结果为:
```
前序遍历: A B C D E F
中序遍历:A B C D E F
后序遍历:A C B F E D
层次遍历: A B C D E F
哈夫曼编码:
A: 10
B: 00
C: 110
D: 111
E: 01
F: 11
```
阅读全文