哈夫曼树实现

本文介绍了一种基于哈夫曼树的编码实现方法。通过构造哈夫曼树,可以为不同字符分配长度不等的编码,使得出现频率较高的字符拥有较短的编码。文章详细展示了如何使用C++实现哈夫曼树的创建过程,并给出具体示例。

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

#include <iostream>
#include <cstdio>
#define inf 1<<30
using namespace std;
//哈夫曼树实现
//哈夫曼树的特征:如果有n个叶子节点的话,则总结点数为2*n-1。越频繁访问的编码越短
struct node
{
	int parent, lson, rson;
	int val;      //访问次数
};

void createTree(node p[], int n, int total)   //total=2*n-1
{
	for(int t=0; t<total; ++t)  //初始化
	{
		p[t].parent = p[t].lson = p[t].rson = -1;
	}
	for(int i=n; i<total; ++i)
	{
		int min1, min2, l, r;   //最大值和第二大值
		min1 = min2 = inf;
		l = r = -1;
		for(int t=0; t<i; ++t)   //遍历寻找两个最小的点,也就是val值最小的
		{
			if(p[t].parent == -1)
			{
				if(p[t].val<min1)
				{
					r = l;
					l = t;
					min2 = min1;
					min1 = p[t].val;
				} else if(p[t].val<min2){
					r = t;
					min2 = p[t].val;
				}
			}
		}
		p[i].val = min1 + min2;
		p[l].parent = p[r].parent = i;
		p[i].lson = l;
		p[i].rson = r;
	}
}

struct code
{
	int k;
	char c[100];
};

void huffmancode(node p[], int n, code c1[])
{
	for(int t=0; t<n; ++t)
	{
		int pre = p[t].parent;
		int g = t;
		c1[t].k = 0;
		while(pre != -1)
		{
			if(p[pre].lson == g)
			{
				c1[t].c[c1[t].k++] = '0';
			} else {
				c1[t].c[c1[t].k++] = '1';
			}
			g = pre;
			pre = p[pre].parent;
		}
		c1[t].k--;
	}
}

int main()
{
	node p[4*2-1];
	for(int t=0; t<4; ++t)
	{
		p[t].val = 2*t+1;
	}
	createTree(p, 4, 2*4-1);
	code c[4];
	huffmancode(p, 4, c);

	for(int t=0; t<4; ++t)
	{
		int k = c[t].k;
		printf("%d:", p[t].val);
		for(int j=k; j>=0; --j)
		{
			printf("%c", c[t].c[j]);
		}
		printf("\n");
	}
	return 0;
}


运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值