数据结构-哈夫曼树用代码实现07

哈夫曼树用代码实现

请看代码:
例子用的上一节,请自行对比

#include<iostream>
#include<deque>
#include<vector>
#include<algorithm>
using namespace std;

typedef struct _HuffumanTree
{
	int weight;//权值
	_HuffumanTree *left;//左儿子节点
	_HuffumanTree *right;//右儿子节点
}HuffumanTree;

//构造哈夫曼树
HuffumanTree * CreateHuffumanTree(vector<int> &m_vc)
{
	deque<HuffumanTree *>m_HfVc;
	//1.根据权值先创建树节点
	for (auto p :m_vc)
	{
		
		HuffumanTree *m_hf = (HuffumanTree *)malloc(sizeof(HuffumanTree));
		m_hf->weight = p;
		m_hf->left = nullptr;
		m_hf->right = nullptr;

		m_HfVc.push_back(m_hf);
	}

	//2.将装有树节点的队列按照从小到大的顺序排列,并且取出最小的两个
	int nsize = m_HfVc.size();
	int a = 0;
	int b = 0;
	HuffumanTree *m_leftChild{ nullptr };//左
	HuffumanTree *m_rightChild{ nullptr };//右
	HuffumanTree* newtree{ nullptr };
	for (int i = 0; i < nsize-1;i++)
	{

		sort(m_HfVc.begin(), m_HfVc.end(), [](HuffumanTree *t1, HuffumanTree *t2){return t1->weight < t2->weight; });
		
		m_leftChild = m_HfVc.front();
		m_HfVc.pop_front();

		m_rightChild = m_HfVc.front();
		m_HfVc.pop_front();

		newtree = (HuffumanTree *)malloc(sizeof(HuffumanTree));
		newtree->weight = m_leftChild->weight + m_rightChild->weight;
		newtree->left = m_leftChild;
		newtree->right = m_rightChild;
		
		m_HfVc.push_back(newtree);
	}

	return  m_HfVc.front();
}

//打印哈夫曼树
void printHfTree(HuffumanTree *root)
{
	if (root)
	{
		cout << root->weight << endl;
		if (root->left)
		{
			cout << root->left->weight << "    ";
		}
		else{
			cout << "没有左孩子\n";
		}

		if (root->right)
		{
			cout << root->right->weight << "    ";
		}
		else{
			cout << "没有右孩子\n";
		}
		cout << endl;
		printHfTree(root->left);
		printHfTree(root->right);

	}


}
void main()
{
	vector<int> m_vc{ 19, 21, 2, 3, 6,7,10,32 };
	
	HuffumanTree *m_hf = CreateHuffumanTree(m_vc);

	printHfTree(m_hf);

	system("pause");
}

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

发如雪-ty

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

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

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

打赏作者

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

抵扣说明:

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

余额充值