[手撕数据结构] 哈夫曼树及哈夫曼编码

代码如下  可直接运行

​
#include<math.h>
#include<stdlib.h>
#include<string>
#include<stdbool.h>
#include<iostream>
using namespace std;
struct HFtree
{
	int weight;     //权值 
	int parents;    //父节点 
	int lchd;       //左孩子 
	int rchd;       //右孩子 
};
void findTwoMin(struct HFtree* data, int* min1, int* min2, int length)//寻找最小的两个值的下标
{
	*min1 = 0;
	*min2 = 0;
	for (int i = 1; i < length; i++)
	{
		if (data[i].parents == 0)
		{
			if (data[i].weight < data[*min1].weight)
				*min1 = i;
		}
	}
	data[*min1].parents = length;//最小权值结点赋值父节点
	for (int i = 1; i < length; i++)
	{
		if (data[i].parents == 0)
		{
			if (data[i].weight < data[*min2].weight)
				*min2 = i;
		}
	}
	data[*min2].parents = length;
}
void printHFtree(struct HFtree* HF, int a)//打印哈夫曼树
{
	cout << "下标    权重     父节点     左孩子      右孩子" << endl;
	for (int i = 1; i < a; i++)
	{
		cout << i << "         " << HF[i].weight << "        " << HF[i].parents << "            " << HF[i].lchd << "          " << HF[i].rchd << endl;
	}

}
void HFcode(struct HFtree* HF, const int n)
{
	if(n<=1)
	{
		cout << "哈夫曼编码为:0";
		return;
	}
		int* stack = (int*)malloc(sizeof(int) * n);//用栈来保存编码值再合适不过了
	if (stack == NULL)//没有足够空间来给栈  虽然一般情况下肯定不会没空间 出于严谨还是加上吧(其实是为了消除编译器给的警告)
	{
		cout << "无足够空间存储哈夫曼编码";
		return;
	}
	for (int i = 1; i <= n; i++)
	{
		int top = -1;
		int par = HF[i].parents;//储存parents变量
		while (par != 0)
		{
			if (HF[par].lchd == i)
			{
				stack[++top] = 0;//入栈   父节点的左子树赋值为0
			}
			else
			{
				stack[++top] = 1;//入栈   父节点的右子树赋值为1
			}
			par = HF[par].parents;
		}
		if(i==1)
		cout << "哈夫曼编码为:"<<endl;
		for (; top >= 0; top--)//出栈   输出哈夫曼编码
		{
			cout << stack[top] << " ";
		}
	}
}

struct HFtree* creatHFtree(int n)//创建哈夫曼树  n为权值的个数;
{
	int a = 2 * n;
	struct HFtree* HF = (struct HFtree*)malloc(sizeof(struct HFtree) * a);
	if (n<2)
	{
		cout << "不需构造";
		return HF;
	}
	if (HF == NULL)
	{
		cout << "空间不足创建失败" << endl;
		free(HF);
		return 0;
	}
	for (int i = 1; i < a; i++)
	{
		HF[i].parents = HF[i].lchd = HF[i].rchd = 0;
	}
	HF[0].weight = 10000;
	cout << "请输入" << n << "个权值" << endl;
	for (int i = 1; i <= n; i++)//输入权重
	{
		cin>>HF[i].weight;
	}
	for (int i = n + 1; i < a; i++)
	{
		int min1, min2;
		findTwoMin(HF, &min1, &min2, i);
		int sum = HF[min1].weight + HF[min2].weight;
		HF[i].weight = sum;
		HF[i].lchd = min1, HF[i].rchd = min2;
	}
	printHFtree(HF, a);
	return HF;
}

int main()
{
	int n;//权的个数
	cout << "输入权的个数: ";
	cin >> n;
	int a = 2 * n;
	struct HFtree* HF = (struct HFtree*)malloc(sizeof(struct HFtree) * a);
	if (HF == NULL)
	{
		cout << "创建失败" << endl;
		free(HF);
		return 0;
	}
	HF = creatHFtree(n);
	HFcode(HF, n);
	system("pause");
	free(HF);
	return 0;
}

​

效果如下

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值