#include<iostream>
using namespace std;
typedef struct HTNode
{
int weight;
int parent,lchild,rchild;
}HTNode;
void Select(HTNode *&HT,int a,int &s1,int &s2)
{
s1=1;
int temp;
while(s1<=a)
{
if(HT[s1].parent==0)
{
break;
}
else s1++;
}
s2=s1+1;
while(s2<=a)
{
if(HT[s2].parent==0)
{
break;
}
else s2++;
}
int i=s2;
if(HT[s1].weight>HT[s2].weight)
{
temp=s1;
s1=s2;
s2=temp;
}
for(int j=i+1;j<=a;j++)
{
if(HT[j].parent==0&&HT[j].weight<HT[s2].weight)
{
if(HT[j].weight<HT[s1].weight)
{
s2=s1;
s1=j;
}
else
{
s2=j;
}
}
}
}
void CreatHfTree(HTNode *&HT,int n)
{
if(n<=1) return;
int m;
int s1,s2;
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 j=1;j<=n;j++)
{
cin>>HT[j].weight;
}
for(int a=n+1;a<=m;a++)
{
Select(HT,a-1,s1,s2);
HT[s1].parent=a;
HT[s2].parent=a;
HT[a].lchild=s1;
HT[a].rchild=s2;
HT[a].weight=HT[s1].weight+HT[s2].weight;
}
}
void outputNode(HTNode *HT,int n)
{
int m;
m=2*n-1;
for(int i=1;i<=m;i++)
cout<<HT[i].weight<<" ";
}
int main()
{
HTNode *HT;
int n;
cout<<"输入你要输入的个数:";
cin>>n;
CreatHfTree(HT,n);
outputNode(HT,n);
return 0;
}
该代码由C++进行编译,代码为创建哈夫曼树,通过输入相应的数值来创建哈夫曼树,显示的为哈夫曼树中每一个结点的权重。