经过一定数量的步骤后停止递归 [英] Stop recursion after a certain amount of steps

查看:56
本文介绍了经过一定数量的步骤后停止递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题使我感到困惑.我有一棵树,我想写一个方法来计算某个节点的孙子代数(但不是大的孙子代).我不能使用循环,只能递归.所以问题是我将如何实现我的基本情况?我如何使其停止?我想不出实现此目标的方式...

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);
    }
}

这篇关于经过一定数量的步骤后停止递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆