哈夫曼树用代码实现
请看代码:
例子用的上一节,请自行对比
#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");
}
结果: