本题是计算二叉树中叶子结点的个数。
函数接口定义:
在这里描述函数接口。例如:
int num (Bptr p);
裁判测试程序样例:
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
int data;
struct node *Lson,*Rson;
}Bnode,*Bptr;
int num (Bptr p);
Bptr creat()
{
Bptr p;
int x;
scanf("%d",&x);
if(x==0)
return NULL;
p=(Bptr)malloc(sizeof(Bnode));
p->data=x;
p->Lson=creat();
p->Rson=creat();
return p;
}
int main()
{
Bptr root;
int k;
root=creat();
k=num(root);
printf("%d\n", k);
return 0;
}
/* 请在这里填写答案 */
输入样例:
3 4 1 0 0 0 2 0 0
输出样例:
2
int num(Bptr p) {
int count = 0;
if (!p->Lson && !p->Rson )
return 1;
if (p->Lson)
count+= num(p->Lson);
if(p->Rson)
count+= num(p->Rson);
return count;
}
遍历所有节点,判断左孩子和右孩子节点都为null的就是叶节点。
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632