哈夫曼树基本原理

首先我们看看基本定义
哈夫曼树的学术定义为,带权路径长度最短的二叉树,即节点具有两个属性:
1、权值,可以看作节点表达出的数值大小,或者变换的表示为概率大小
2、路径,可以看作由根节点到达当前节点的分支数,左分支和右分支具有不同意义
带权路径长度即为权值与路径乘积的累加,所以哈夫曼树首先是一棵二叉树,其次通过调整二叉树节点位置,使得带权路径长度最小。
综上也就是把每个节点合并为根节点的左右节点,且每次选择合并时要使得根节点最小。哈夫曼树是从根部往下走越来越小

 A

 

此图片较好说明了生成步骤可以参考理解

 直接上代码

#include<iostream>
#include <vector>
#include<queue>
#include <functional>
using namespace std;
struct node
{
	int data;
	node*ltree;
	node*rtree;
	node()
	{
		ltree = rtree = NULL;
	}
	node(int data)
	{
		this->data = data;
		ltree = rtree = NULL;
	}
};
struct Huffmantree 
{
	node *root;
	Huffmantree(){
		root = NULL;
	}
	Huffmantree(int weight){ root = new node(weight); }
	Huffmantree(vector<Huffmantree>&nodes)
	{
		Huffmantree tmp;
		priority_queue<Huffmantree, vector<Huffmantree>, greater<Huffmantree>>q(nodes.begin(), nodes.end());
		for (int i = 1; i<nodes.size();i++)
		{
			tmp.root = new node;
			tmp.root->ltree = q.top().root; q.pop();
			tmp.root->rtree = q.top().root; q.pop();
			tmp.root->data = tmp.root->ltree->data + tmp.root->rtree->data;
			q.push(tmp);
		}
		root = q.top().root;
	}
	bool operator >(const Huffmantree &t)const{
		return this->root->data > t.root->data;
	}
	void print()
	{
		rprint(root, 0);
	}
	void rprint(node *r,int depth)
	{
		for (int i = 0; i < depth;i++)
		{
			cout << " ";
		}
		if (!r)
		{
			cout << "[/]"<< endl;
		}
		else
		{
			
				cout << r->data << endl;					
		
				rprint(r->ltree, depth + 1);
			
			
				rprint(r->rtree, depth + 1);
			
			
		}
	}
};

void main()
{
	int nv, weight;
	cin >> nv;
	vector<Huffmantree>nodes;
	for (int i = 0; i < nv;i++)
	{
		cin >> weight;
		nodes.emplace_back(weight);
	}
	Huffmantree ht(nodes);
	ht.print();
	system("pause");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LV小猪精

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值