递归学习中。。。。。感觉这个题主要就是递归的运用,代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
typedef struct Node
{
int val;
struct Node *left,*right;
} Node;
int n,m;
int num[85];
Node *buildtree()
{
scanf("%d",&n);
Node *u=(Node *)malloc(sizeof(Node));
if(n==-1)
return NULL;
u->val=n;
u->left=buildtree();
u->right=buildtree();
return u;
}
void look(Node *root)
{
if(root==NULL) {printf("-1 ");return ;}
printf("%d ",root->val);
look(root->left);
look(root->right);
}
void search(int mid,Node *root)
{
if(root==NULL) return ;
num[mid]+=root->val;
search(mid-1,root->left);
search(mid+1,root->right);
}
int main()
{
/*freopen("in.txt","r",stdin);*/
int mid=42,i,j,cas=1;
while(1)
{
Node *root=(Node *)malloc(sizeof(Node));
root=buildtree();
/*look(root);*/
memset(num,0,sizeof(num));
search(mid,root);
for( i=0; num[i]==0&&i<85; i++);
if(i==85) return 0;
for(j=84; num[j]==0&&j>=0; j--);
printf("Case %d:\n",cas++);
printf("%d",num[i++]);
for(; i<=j; i++)
printf(" %d",num[i]);
putchar('\n'); putchar('\n');
}
return 0;
}
buildtree()函数是用的返回值的形式,look函数,search函数用的是无返回值,传参数的形式,注意递归时每一层都有一个属于自己这一层的u,压入栈,而不是定义一个全局变量u作为参数传递。