使用C++实现 哈夫曼树(创建和打印)
#include <iostream>
#include <map>
using namespace std;
typedef struct
{
int weight;
int parent, lchild, rchild;
} HTNode, *HuffmanTree;
void Select(HuffmanTree &HT, int n, int &s1, int &s2)
{
map<int, int> m;
for (int i = 1; i <= n; i++)
{
if (HT[i].parent == 0)
{
m.insert(make_pair(HT[i].weight, i));
}
}
map<int, int>::iterator it = m.begin();
s1 = (*it).second;
it++;
s2 = (*it).second;
}
void CreateHuffmanTree(HuffmanTree &HT, int n)
{
if (n <= 1)
return;
int m = 2 * n - 1;
HT = new HTNode[m + 1];
for (int i = 1; i <= m; i++)
{
HT[i].parent = 0;
HT[i].lchild = 0;
HT[i].rchild = 0;
}
for (int i = 1; i <= n; i++)
{
cin >> HT[i].weight;
}
for (int i = n + 1; i <= m; i++)
{
int s1, s2;
Select(HT, i - 1, s1, s2);
HT[s1].parent = i;
HT[s2].parent = i;
HT[i].lchild = s1;
HT[i].rchild = s2;
HT[i].weight = HT[s1].weight + HT[s2].weight;
}
}
void PrintHuffmanTree(HuffmanTree &HT, int n)
{
cout << "index" << '\t' << "weight" << '\t' << "parent" << '\t' << "lChild" << '\t' << "rChild" << endl;
for (int i = 1; i <= 2 * n - 1; ++i)
{
cout << i << "\t";
cout << HT[i].weight << '\t';
cout << HT[i].parent << "\t";
cout << HT[i].lchild << "\t";
cout << HT[i].rchild << endl;
}
}
int main()
{
HuffmanTree hf;
CreateHuffmanTree(hf, 5);
PrintHuffmanTree(hf, 5);
}