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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...