#include<stdio.h>
#include<string.h>
#include<iostream.h>
#define maxbit 100
#define maxvalue 100
#define maxleaf 100
#define maxnode maxleaf*2-1
typedef struct {
int weight;//权重值
int parent;
int lchild;//指针域
int rchild;
char h;
}hnodetype;//定义节点结构
typedef struct{
int bit[maxbit];//编码域
int start;//记录编码在数组中开始位置
}hcodetype;//定义编码类型,存储个字符信息
hnodetype huffnode[maxnode];
hcodetype huffcode[maxleaf];
void haffmantree( int *x){
int i,j,n;
int m1,m2,x1,x2;
cout<<"请输入叶子节点数"<<endl;
cin>>n;
for(i=0;i<2*n-1;i++){//初始化各节点
huffnode[i].weight=0;
huffnode[i].parent=-1;
huffnode[i].lchild=-1;
huffnode[i].rchild=-1;
}
*x=n;
cout<<"请输入"<<n<<"个节点的信息(权重+字符)"<<endl;
for(i=0;i<n;i++)//权重赋值
{
cin>>huffnode[i].weight>>huffnode[i].h;
cout<<huffnode[i].h<<"----"<<huffnode[i].weight<<endl;
}
for(i=0;i<n-1;i++)//构造哈夫曼树
{
m1=m2=maxvalue;
x1=x2=0;
for(j=0;j<n+i;j++){//选取最小和次小两个权值
if(huffnode[j].parent==-1&&huffnode[j].weight<m1){
m2=m1;
x2=x1;m1=huffnode[j].weight;
x1=j;
}
else
if(huffnode[j].parent==-1&&huffnode[j].weight<m2){
m2=huffnode[j].weight;
x2=j;
}
}
huffnode[x1].parent=n+i;
huffnode[x2].parent=n+i;