本文介绍了经过一定数量的步骤后停止递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题使我感到困惑.我有一棵树,我想写一个方法来计算某个节点的孙子代数(但不是大的孙子代).我不能使用循环,只能递归.所以问题是我将如何实现我的基本情况?我如何使其停止?我想不出实现此目标的方式...
This problem is confusing me. I have a tree, and I want to write a method that counts the number of grandchildren of a certain node (but not great granchildren). I cant use loops, only recursion. So the question is how would I implement my base case? How do I make it stop? I can't think of a way that this would be implemented...
推荐答案在递归方法中具有 depth 参数,并在自调用之前将其加1,即:
Have a depth argument to your recursive method, and have it add 1 before it self-calls, i.e.:
void myMethod(int depth) { /* ... Do something ... */ if (depth < maxDepth) { child.myMethod(depth + 1); } }更多推荐
经过一定数量的步骤后停止递归
发布评论