- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Turning Recursion Into Iteration
Recursion
Turning Recursion Into Iteration
Recursion uses the call stack. An iterative version uses a stack you control. The logic is identical; the difference is that your stack lives on the heap and does not overflow at ten thousand frames.
When you are forced to
- Depth grows with input size and the input can be large.
- You are processing user data of unknown shape - a deeply nested JSON payload will crash a recursive walk.
- You need to pause, resume or cancel partway through.
The simple case: no combining
When the recursion just visits things and does not combine results, the conversion is mechanical - push instead of call.
Tree walk, both ways
javascript
