One of Codility tasks is to find the height of a binary tree. The task guarantees that the height won't exceed 500. So the easiest solution that comes to mind is to just use recursion.
Now, while such a solution passes all the tests in Codility I wonder if I can safely assume 500 is not too much (for any computer/test platform that's likely to be Codility's test platform) or whether I should avoid recursion and either simulate it or find the height of the tree some other way?
Edit: As PM 77-1 pointed out, the answer might depend on what my recursion looks like. So I've included it. There's a struct
defined:
struct tree {
int x;
tree * l;
tree * r;
};
And here is my solution:
int getHeight(tree const * T, int height)
{
int maxHeight = height;
if (T->l)
{
maxHeight = getHeight(T->l, height + 1);
}
if (T->r)
{
maxHeight = max(maxHeight, getHeight(T->r, height + 1));
}
return maxHeight;
}
int solution(tree * T)
{
return getHeight(T, 0);
}
Now my question is - knowing how my solution looks like (how much memory it can use/etc...) and NOT knowing what the test platform specs are can I safely assume 500 recursive calls won't cause a stack overflow or not? (Because if it were 50 or 5 I think I could safely assume that no matter the test platform.)
Edit: I deliberately haven't specified the language as Codility supports a multitude of them and I'd like to get an answer concerning more than one, if possible. However, I was using C++ in my solution so I guess that's the language I'm most interested in.