Huffman Tree Algorithm
用了优先队列来存储节点,权重小的先输出。需要注意的是为节点写比较函数
的方法,因为这时优先队列存储的是节点的指针,不可以将比较函数直接写在类里
,这时可以用一下的方法。
(为备战英语六级,注释采用英文,相信很易理解,欢迎留言)
#include<iostream>
#include<stdio.h>
#include<string>
#include<queue>
#include<vector>
using namespace std;
const int Maxn = 1000;
struct node{
int val; //the important rank of a node
string code; //huffman code
node* left;
node* right;
//node* parent;
node(int data, node* l, node* r){
val = data;
right = r;
left = l;
}
};
//node that pq is the container for pointer, the compare method
//can't not write in the class. It times need to wirte the
//compare method as an struct.
struct cmp{
bool operator()(const node* a, const node* b){
return a->val > b->val;
}
};
priority_queue<node* ,vector<node*>, cmp> pq;
//set huffman code for each node according to the final
void set_code(node* n){
if (n->left == NULL && n->right == NULL){
cout << n->val<<" --> "<< n->code << endl;
return;
}
if (n->left != NULL){
n->left->code += n->code + "0";
set_code(n->left);
}
if (n->right != NULL){
n->right->code += n->code + "1";
set_code(n->right);
}
return;
}
int main(){
int n;
cin >> n;
//input data
for(int i = 0; i < n;i++){
int temp;
cin >> temp;
node* tn = new node(temp, NULL, NULL);
pq.push(tn);
}
//build an Huffman tree
while (pq.size()>1){
node* t1 = pq.top();
pq.pop();
node* t2 = pq.top();
pq.pop();
node* newnode = new node(t1->val + t2->val, t1, t2);
pq.push(newnode);
}
node* head = pq.top();
set_code(head);
return 0;
}
本文介绍了使用C++编程实现哈夫曼树算法的过程,重点在于利用优先队列来存储节点,并且详细说明了如何处理节点比较函数的细节,以便正确地构建和操作哈夫曼树。

1562

被折叠的 条评论
为什么被折叠?



