求二叉树第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

 

posted @ 2017-03-10 15:22  willhua  阅读(4731)  评论(0编辑  收藏  举报