Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

java - Stop recursion after a certain amount of steps

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...