uva 699 The Falling Leaves

本文通过一个具体的递归实现案例,介绍了如何使用递归构造二叉树并进行遍历及节点值累加操作。详细解释了递归函数的定义与调用过程,包括构建树、查看树结构和搜索节点值等。

         递归学习中。。。。。感觉这个题主要就是递归的运用,代码:

#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作为参数传递。



    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值