Snowman
Snowman

Reputation: 32071

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

Upvotes: 3

Views: 5689

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

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

Upvotes: 11

Oded
Oded

Reputation: 499132

Pass in a "recursion depth" parameter to your recursive function, incrementing it for every call to the function.

When you hit your limit, you stop recursing.

Upvotes: 2

Related Questions