#include
#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=m1+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=m2+1;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++;
}
}
void codeHT(struct HTree *ht){
int count=(ht->length+1)/2;
int weightdata[count];
for(int i=0;ibody[i].weight;
}
char *ch[count];
char a[count];
int index=0;
for(int i=0;ilength;i++){
ht->body[i].weight=0;
}
int cur=ht->length-1;
while(cur!=-1){
if(ht->body[cur].weight==0){
ht->body[cur].weight=1;
if(ht->body[cur].lchild!=-1){
a[index++]='0';
cur=ht->body[cur].lchild;
}else{
a[index]=' ';
ch[cur]=(char *)malloc(sizeof(char)*count);
strcpy(ch[cur],a);
}
}else if(ht->body[cur].weight==1){
ht->body[cur].weight=2;
if(ht->body[cur].rchild!=-1){
a[index++]='1';
cur=ht->body[cur].rchild;
}
}else{
ht->body[cur].weight=0;
cur=ht->body[cur].parent;
index--;
}
}
printf("最优前缀码:n");
for(int i=0;i