结训赛第一次复习:二叉树的基本操作(二)

二叉树的层序遍历:

http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2711/pid/3344

这道题需要联系前面的:栈和队列

节约时间只输出函数

void cengxu(struct tree*root)
{
    int in,out;
    struct tree*temp[55];
    in=0;
    out=0;
    temp[in]=root;
    if(in>out)
    {
        if(temp[out])//保证输出有数,注意不要用in,因为如果in在NULL停,那么剩下的out++就没来
        {
            printf("%c",temp[out]->data);
            temp[in++]=temp[out]->l;//左儿子进
            temp[in++]=temp[out]->r;//右儿子进
        }
        out++;
    }
}

让我们手动debug,还是建一个最简单的树abc,因为这书结构体指针数组,首先储存树根,在保证in>out情况下,把a输出,然后在把左右孩子放进队列,接下来同理

统计叶子数,就是统计最下面的孩子(他下面左右孩子都为空)

参考大佬文章:https://blog.csdn.net/zhangkongzhongyun/article/details/38037059

http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2711/pid/3342

void searchleaf(struct node*root)
{
    if(root)
    {
        if(root->l==NULL&&root->r=NULL)
        {
            count++;
        }
        searchleaf(root->l);
        searchleaf(root->r);
    }
    return count;
}

手动debug:建一个abc树,首先searchleaf(root->l)->然后因为b下面是NULL所以count++,然后直接search(root->r),发现下面是NULL所以说count加俩次,同理其他更复杂的树也是同理

扫描二维码关注公众号,回复: 12164770 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_44067773/article/details/87867662