#include<iostream>
using namespace std;
#define MaxWeight 100
typedef struct HTNode
{
int weight;
int parent, lch, rch;
bool visit;
}HTNode, *HuffmanTree;
void Select(HuffmanTree HT, int i, int& s1, int& s2) //挑选权值最小的两个结点
{
int sm1, sm2;
sm1 = sm2 = MaxWeight;
for(int j=0; j<=i; ++j)
{
if(HT[j].weight<sm1&&!HT[j].visit)
{
sm1 = HT[j].weight;
s1 = j;
}
}
HT[s1].visit = true;
for(int j=0; j<=i; ++j)
{
if(HT[j].weight<sm2&&!HT[j].visit)
{
sm2 = HT[j].weight;
s2 = j;
}
}
HT[s2].visit = true;
}
void CreatHuffmanTree(HuffmanTree& HT, int n)
{
int m = 2*n-1; //数组最终有2*n-1个元素
HT = new HTNode[m];
for(int i=0; i<m; ++i) //初始化各个结点
{
HT[i].lch = HT[i].rch = HT[i].parent = -1;
HT[i].visit = false;
}
for(int i=0; i<n; ++i) //输入各个结点的权重
{
cin >> HT[i].weight;
}
for(int i=n; i<m; ++i)
{
int s1, s2;
Select(HT, i-1, s1, s2); //从HT[k](0=<k<=i-1)中没有双亲结点的结点中找出权重最小的两个结点的位置
HT[i].weight = HT[s1].weight + HT[s2].weight ;
HT[i].lch = s1;
HT[i].rch = s2;
HT[s1].parent = HT[s2].parent = i;
}
}
int main()
{
HuffmanTree HT;
int n = 8;
CreatHuffmanTree(HT, n);
for(int i=0; i<2*n-1; ++i)
{
cout << HT[i].weight << " " << HT[i].parent << " " << HT[i].lch << " " << HT[i].rch << endl;
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq_46027243/article/details/113867404
内容来源于网络,如有侵权,请联系作者删除!