求二叉树第n层节点数

在知乎看到今日头条的一个面试题“求二叉树第n层节点数”:https://zhuanlan.zhihu.com/p/25671699,想到了这样一个解法,欢迎大家交流

 

我的解法采用递归的思想,从0层开始,逐层往下递归。然后达到递归终止条件时(cur == goal - 1),就会把n-1层的所有儿子数都统计上来,代码如下:

 1 int CountChildNum(Tree *t, int n)
 2 {
 3     if(NULL == t)
 4         Error("fatal error");
 5     if(n == 0)
 6         return 1;
 7     return CountChild(t, 0, goal);
 8 }
 9 
10 //cur:递归到的当前层, goal:目标层
11 int CountChild(Tree *t, int cur, int goal)
12 {
13     if(NULL == t || cur >= goal)
14         return 0;
15     
16     int c = 0;
17     if(cur == goal - 1) //此时t的儿子即为想要的层数
18     {
19         if(t -> left != NULL)
20             ++c;
21         if(t -> right != NULL)
22             ++c;
23     }
24     else
25     {
26         c += CountChild(t -> left, cur + 1, goal);
27         c += CountChild(t -> right, cur + 1, goal);
28     }
29     return c;
30 }

 

这里有更好的解法:

http://www.cnblogs.com/hapjin/p/5505988.html

轻松搞定面试中的二叉树题目

http://blog.csdn.net/luckyxiaoqiang/article/details/7518888

 

转载于:https://www.cnblogs.com/willhua/p/6530879.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值