基础数据结构算法_哈夫曼树

本文介绍了哈夫曼树的基础知识及其在数据压缩中的应用。通过使用优先级队列,按照字符频率从小到大的顺序合并元素,逐步构建哈夫曼树。详细实现过程可从代码中了解。
摘要由CSDN通过智能技术生成

哈夫曼树还是比较实用的,又简单。

具体的实现方法:设一个优先级队列,频率越小的字母越优先。

每次都从队列中取出最前面两个元素,合并成一个新的元素。

直到元素只剩一个。

具体的实现细节看代码吧。

                #include<iostream>
		#include<vector>
		#include<string>
		#include<queue>
		using namespace std;
		
		typedef struct node
		{
			char m;
			int v;
			node *left,*right;
		}node;
		
		typedef struct comp
		{
			bool operator () (node *a,node *b)
			{
				return a->v>b->v;
			}
		}comp; 
		
		void outcode(node* T,string &s)//输出编码 用引用节约空间 
		{
			if(T->left!=NULL)
			{
				s.push_back('0');
			    outcode(T->left,s);
			    s.pop_back();
			}
			if(T->right!=NULL)
			{
				s.push_back('1');
			    outcode(T->right,s);
			    s.pop_back();
			}
			if(T->left==NULL&&T->right==NULL)
			{
				cout<<T->m<<" "<<s<<endl;
			}
		}
		
		int main()
{
	    int n;
	    cin>>n;
	    priority_queue<node*,vector<node*>,comp> q;//利用优先级队列 
	    for(int i=0;i<n;i++)
	    {
	    	node *temp=new node;
	    	cin>>temp->m>>temp->v;
	    	temp->left=temp->right=NULL;
	    	q.push(temp);
		}
		
		while(q.size()>=2)//建树 
		{
			node* temp=new node;
			temp->v=q.top()->v;
			temp->left=q.top();
			q.pop();
			temp->v+=q.top()->v;
			temp->right=q.top();
			q.pop();
			q.push(temp);	
		}
	    
	    string s="";
	    outcode(q.top(),s);//输出对应的编码
	    
	    return 0; 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值