数据结构之二叉树三:统计叶子数

如果把二叉树的建立中的递归理解透彻了,那么这个题目就非常简单了,只需要加上一个判断条件和一个计数变量即可;


题目如上:

代码如下:

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    char data;
    struct node *lchild,*rchild;
}node,*nodeptr;

char a[55];
int i,count;

struct node *Creat(struct node *T)
{
    T=(struct node *)malloc(sizeof(struct node));
    if(a[i++]==',')T=NULL;
    else
    {
        T->data=a[i-1];
        T->lchild=Creat(T->lchild);
        T->rchild=Creat(T->rchild);

    }
    return T;
}

int Countleaf(struct node *T)
{
    if(T)
    {
        if((!T->rchild)&&(!T->lchild))
        {//判断是否是叶子节点,利用叶子节点的特点
            count++;
        }
        Countleaf(T->lchild);
        Countleaf(T->rchild);
    }
    return count;
}


int main()
{
    struct node *T;
    while(~scanf("%s",a))
    {
        T=Creat(T);
        count=0;
        i=0;
        printf("%d\n",Countleaf(T));
    }
    return 0;
}

对这个代码不是很理解的可以先理解一下上面这一个二叉树遍历的递归过程,关联的文章

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值