#include
#include
#include
struct HTreeNode{
int parent;
int lchild;
int rchild;
int weight;
};
struct HTree{
struct HTreeNode *body;
int length;
};
struct HTree *iniHTree(int num){
struct HTree *ht;
ht=(struct HTree *)malloc(sizeof(struct HTree));
int size=2*num-1;
ht->body=(struct HTreeNode *)malloc(sizeof(struct HTreeNode)*size);
ht->length=0;
int i;
for(i=0;ibody[i].parent=-1;
ht->body[i].lchild=-1;
ht->body[i].rchild=-1;
int temp;
printf("The %dth weight=",i);
scanf("%d",&temp);
ht->body[i].weight=temp;
ht->length++;
}
for(;ibody[i].parent=-1;
ht->body[i].lchild=-1;
ht->body[i].rchild=-1;
ht->body[i].weight=pow(2,31)-1;
}
return ht;
}
void show(struct HTree *ht){
if(ht->body!=NULL){
for(int i=0;ilength;i++){
printf("%4d",ht->body[i].lchild);
printf("%4d",ht->body[i].weight);
printf("%4d",ht->body[i].rchild);
printf("%4d",ht->body[i].parent);
printf("n");
}
}
}
void findTwoMinHTNode(struct HTree *ht,int *min1,int *min2){
int m1,m2;
int minWeight;
int j=0;
while(ht->body[j].parent!=-1){
j++;
}
m1=j;
minWeight=ht->body[m1].weight;
for(int i=1;ilength;i++){
if(ht->body[i].parent==-1&&ht->body[i].weightbody[i].weight;
}
}
ht->body[m1].parent=1;
*min1=m1;
j=0;
while(ht->body[j].parent!=-1){
j++;
}
m2=j;
minWeight=ht->body[m2].weight;
for(int i=0;ilength;i++){
if(ht->body[i].parent==-1&&ht->body[i].weightbody[m2].weight;
}
}
*min2=m2;
ht->body[m2].parent=1;
}
void consummateHT(struct HTree *ht,int num){
if(ht==NULL){
printf("HT is not exitn");
return;
}
int min1,min2;
for(int i=num;i<2*num-1;i++){
findTwoMinHTNode(ht,&min1,&min2);
ht->body[min1].parent=i;
ht->body[min2].parent=i;
ht->body[i].lchild=min1;
ht->body[i].rchild=min2;
ht->body[i].weight=ht->body[min1].weight+ht->body[min2].weight;
ht->length++;
}
}
int main(){
struct HTree *ht;
int num;
printf("leaf=");
scanf("%d",&num);
ht=iniHTree(num);
consummateHT(ht,num);
printf("哈夫曼树存储表如下:n");
show(ht);
return 0;
}