c++写哈夫曼编码树算法

本文介绍了使用C++编程实现哈夫曼树算法的过程,重点在于利用优先队列来存储节点,并且详细说明了如何处理节点比较函数的细节,以便正确地构建和操作哈夫曼树。

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值