主题:[讨论]怎么输出不了哈夫曼树呀.......请各位大侠帮忙!!
#include<stdio.h>
#define maxsize 100
typedef struct node
{
int data;
char name;
int pat,lc,rc;
}hafman[maxsize];
1 void hafmantree(hafman h)
{
int n,i;
2 scanf("%d",&n);
3 for(i=1;i<=2*n-1;i++)
{
4 h[i].pat=0;
5 h[i].lc=0;
6 h[i].rc=0;
7 if(i<=n)scanf("%d %c",&h[i].data,&h[i].name);
8 else h[i].data=0;h[i].name=0;
}
9 for(i=1;i<n;i++)
{
int x=0,y=0,min=32767,smin=32767; 10 for(j=1;j<n+i-1;j++)
11 if(!h[j].pat && h[j].data<min)
{
12 smin=min;y=x;x=j;min=h[j].data;}
13 else if(!h[j].pat && h[j].data<smin)
{
14 y=j;smin=h[j].data;
}
h[x].pat=n+i;
h[y].pat=n+i;
h[n+i].data=min+smin;
h[n+i].lc=x ;
h[n+i].rc= y ;
h[0].data=2*n-1;
}
15 void bianma(hafman h)
{
int stack[maxsize],top,j=1;
int n=(h[0].data+1)/2
while(j<=n)
{ int i=j;
top=-1 ;
while(i!=2*n-1) {
if(h[h[i].pat].lc== i) stack[++top ]=0; else stack[++top ]=1;
}
if(h[h[i].pat].rc== i)
i=h[i].pat;
}
while(top>=0)
{
printf("%d",stack[top--]);
}
printf("\n");
j++;
}
}
void main()
{
hafman ht;
hafmantree(ht);
bianma(ht );
}
#define maxsize 100
typedef struct node
{
int data;
char name;
int pat,lc,rc;
}hafman[maxsize];
1 void hafmantree(hafman h)
{
int n,i;
2 scanf("%d",&n);
3 for(i=1;i<=2*n-1;i++)
{
4 h[i].pat=0;
5 h[i].lc=0;
6 h[i].rc=0;
7 if(i<=n)scanf("%d %c",&h[i].data,&h[i].name);
8 else h[i].data=0;h[i].name=0;
}
9 for(i=1;i<n;i++)
{
int x=0,y=0,min=32767,smin=32767; 10 for(j=1;j<n+i-1;j++)
11 if(!h[j].pat && h[j].data<min)
{
12 smin=min;y=x;x=j;min=h[j].data;}
13 else if(!h[j].pat && h[j].data<smin)
{
14 y=j;smin=h[j].data;
}
h[x].pat=n+i;
h[y].pat=n+i;
h[n+i].data=min+smin;
h[n+i].lc=x ;
h[n+i].rc= y ;
h[0].data=2*n-1;
}
15 void bianma(hafman h)
{
int stack[maxsize],top,j=1;
int n=(h[0].data+1)/2
while(j<=n)
{ int i=j;
top=-1 ;
while(i!=2*n-1) {
if(h[h[i].pat].lc== i) stack[++top ]=0; else stack[++top ]=1;
}
if(h[h[i].pat].rc== i)
i=h[i].pat;
}
while(top>=0)
{
printf("%d",stack[top--]);
}
printf("\n");
j++;
}
}
void main()
{
hafman ht;
hafmantree(ht);
bianma(ht );
}