Follow

I've been conducting more interviews lately, some of which involve traversing a tree / graph, and I am kind of surprised to find that uniformly everyone does these traversals with recursion. I'm not surprised to find that it's popular (I think it's often taught as an example of something where recursion is appropriate), but I personally almost never use recursion (especially in Python).

I think the main reasons I almost always avoid recursion (both in interviews and in practice) are:

1. I prefer to be very explicit about the resources I am using. It's easy to not realize how much overhead you are storing in the frame stack, whereas when you have an explicit stack or queue of nodes, it's quite easy to see what you are storing and passing up and down the stack.
2. No running into recursion limits (mostly Python specific thing).
3. It's pretty easy to switch between depth and breadth first searches by changing from a stack to a queue and vice-versa, whereas if you change your mind and decide you need to do BFS when you've written a recursive traversal, you have to rip everything out and start over.
4. When I need access to some resources outside of the traversal (either to modify them or for some other reason), it seems cleaner to use a variable that is already in scope rather than a closure (though maybe that's a dubious distinction).

Looking at this list, I do think that (other than the recursion limit thing), this is mostly just a bias against recursive functions. I think the primary benefit of a recursive function is that I think it's easier to pivot to a concurrent traversal by spawning multiple child nodes and letting the stack handle your resolution order for you.

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.