回覆列表
  • 1 # 觀球交友

    #include<stdio.h>#include<malloc.h>typedef struct { int data; struct Node*left; struct Node*right;}Node;int s(int *a,int len)//求和函式 { int i=0,sum=0; for(;i<len;i++) sum+=a[i]; return sum;}int search(Node*node,int sum,int *now,int len)//遞迴搜尋 { int i=0,t1=0,t2=0; if(node->left==NULL&&node->right==NULL) { now[len++]=node->data; if(s(now,len)==sum) { FILE*fout=fopen("output.txt","a+"); for(i=0;i<len;i++) fprintf(fout,"%d ",now[i]); fprintf(fout,"\n"); fclose(fout); return 1; } else return 0; } else { now[len]=node->data; if(node->left!=NULL)t1=search(node->left,sum,now,len+1); if(node->right!=NULL)t2=search(node->right,sum,now,len+1); return t1||t2; }}int main(){ int sum,num_node,root,lchild,rchild,front=0,back=0,temp,len=0; Node*node; int*now; FILE*fin=fopen("input.txt","r"); FILE*fout; fscanf(fin,"%d%d",&sum,&num_node); now=malloc(sizeof(int)*num_node); node=(Node*)malloc(sizeof(Node)*num_node); while(fscanf(fin,"%d%d%d",&root,&lchild,&rchild)!=EOF) { if(front==0) node[back++].data=root; if(node[front].data!=root) { fout=fopen("output.txt","w"); fprintf(fout,"ERROR\n"); return 1; } else { temp=front; if(lchild==-1)node[temp].left=NULL; else { node[back].data=lchild; node[temp].left=&node[back]; back++; } if(rchild==-1)node[temp].right=NULL; else { node[back].data=rchild; node[temp].right=&node[back]; back++; } front++; } }//建樹 if(search(node,sum,now,len)==0) { fout=fopen("output.txt","w"); fprintf(fout,"NULL\n"); fclose(fout); } fclose(fin);return 0;}

  • 中秋節和大豐收的關聯?
  • 坐火車行李太重舉不上去怎麼辦?