#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
struct HaffNode{
int val;
HaffNode *lc, *rc;
HaffNode () : val(0), lc(nullptr), rc(nullptr) {}
HaffNode (int _val) : val(_val), lc(nullptr), rc(nullptr) {}
bool operator < (const HaffNode *&A) const {
return val < A->val;
}
};
class compare{
public:
bool operator()(HaffNode *&A, HaffNode *&B) const {
return A->val > B->val;
}
};
int n;
HaffNode* CreatHTnode (int *a)
{
if (n == 1) return NULL;
priority_queue<HaffNode*, vector<HaffNode*>, compare> q;
while (!q.empty()) q.pop();
for (int i = 1; i <= n; i ++) {
HaffNode *x = new HaffNode(a[i]);
q.push(x);
}
HaffNode *root = NULL;
for (int i = 1; i < n; i ++) {
HaffNode *x = q.top(); q.pop();
HaffNode *y = q.top(); q.pop();
cout << x->val << " " << y->val << endl;
HaffNode *fa = new HaffNode(x->val + y->val);
fa->lc = x;
fa->rc = y;
q.push(fa);
if (i == n-1) root = fa;
}
return root;
}
int s[N];
void HaffCode(HaffNode *&T, int lev, int op)
{
s[lev] = op;
if (!T->lc && !T->rc) {
cout << T->val << endl;
for (int i = 1; i <= lev; i ++) cout << s[i];
cout << endl << endl;
return;
}
if (T->lc) HaffCode(T->lc, lev + 1, 0);
if (T->rc) HaffCode(T->rc, lev + 1, 1);
}
void preOrder(HaffNode *&T)
{
if (T == NULL) return;
cout << T->val << " ";
if (T->lc) preOrder(T->lc);
if (T->rc) preOrder(T->rc);
}
void midOrder(HaffNode *&T)
{
queue<HaffNode*> q;
q.push(T);
while (!q.empty()) {
HaffNode *u = q.front(); q.pop();
cout << u->val << " ";
if (u->lc) q.push(u->lc);
if (u->rc) q.push(u->rc);
}
}
int main()
{
ios::sync_with_stdio(0);
n = 4;
int a[] = {0, 7, 3, 5, 1 };
HaffNode* root = CreatHTnode (a);
// midOrder(root);
HaffCode(root, 0, 0);
return 0;
}
利用优先队列建立哈夫曼树并输出哈夫曼编码
最新推荐文章于 2023-06-04 10:35:51 发布