Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

How to avoid stack overflow with recursion?

avoid overflow recursion stack
0
Posted

How to avoid stack overflow with recursion?

0

(1) Use tail-end recursion: that allows you to work on linear structures without additional stack requirements. Doing explicit tail-end recursion can be seen as converting the recursion into an iteration [see sample code]. (2) On non-linear structures [e.g. balanced trees] take the shorter route first [and the rest as tail-end recursion]: that will cut the recursion depth to less than log2 of the input size. Such a small recursion depth will likely not produce an overflow. Sample: reasonable quick sort implementations. It might not be so easy to recognize the shortest path [as it is with quick sort; consider the problem of finding a way out of a labyrinth solved by backtracking: at each step you don’t know in advance which direction will conceal the longest path]. (3) If one can figure out a reasonable upper limit for log2 of the problem size, that can be used to limit the search depth: if that limit is reached, give up and try (all) other branches first; performance will suffer and ma

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123