c++使用优先队列来构建huffman树[哈夫曼树]

本文介绍了一种使用优先队列构建霍夫曼树的方法,并实现了字符频率统计及霍夫曼编码生成的功能。通过输入一组字符及其出现频率,程序能够构建出相应的霍夫曼树并为每个字符分配霍夫曼编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream> #include <queue> #include <string.h> #include <vector> #include <algorithm> using namespace std; char Table[26]; struct Node { int freq; char val; Node * left; Node * right; Node():left(NULL), right(NULL) , freq(0) , val('0'){} }; class Cmp { public: bool operator() (const Node * a, const Node * b) const { return a->freq > b->freq; // 从小到大 ,freq 小的 优先级别高 } }; priority_queue<Node* , vector<Node*> , Cmp> myQueue; void BuildTree() { for (int i = 0; i < 26; ++ i) { if (Table[i] > 0) { Node * node = new Node(); node->freq = Table[i]; node->val =(char) (i + 'A'); myQueue.push(node); } } while (myQueue.size() > 1) { Node * f = myQueue.top(); myQueue.pop(); Node * s = myQueue.top(); myQueue.pop(); Node * tmp = new Node(); tmp->freq = f->freq + s->freq; tmp->left = f; tmp->right = s; myQueue.push(tmp); } //cout << myQueue.top()->freq<<endl; } struct PrintNode { int freq; char val; string code; }; vector<PrintNode> vpn; bool cmp(const PrintNode & a , const PrintNode & b) { return a.freq > b.freq; } void Print( Node * node , string res) { if (node == NULL) { return; } if (node->val != '0') { PrintNode pn; pn.val = node->val; pn.freq = node->freq; pn.code = res; vpn.push_back(pn); //cout <<node->val <<" | " << node->freq <<" | "<< res <<endl; return ; } Print(node->left , res + "0"); Print(node->right, res + "1"); delete node->left; delete node->right; } int main() { int N; memset(Table , 0 , sizeof(Table)); cin >> N; for (int i = 0; i < N; ++i) { char ch ; cin >> ch; if (ch >= 'A' && ch <= 'Z') { ++Table[ch - 'A']; } } BuildTree(); Node * root = myQueue.top(); myQueue.pop(); Print(root , ""); sort(vpn.begin() , vpn.end() , cmp); for (int i = 0; i < vpn.size(); ++i) { cout <<vpn[i].val << " "<<vpn[i].freq <<" " << vpn[i].code<<endl; } return 0; }
具体的构成算法不再这里讨论了,


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值