Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Stack Depth and Iterative DFS

โญโญโญ advancedโณ 30 min read๐Ÿ“ Lesson 186 of 281

A bamboo of 200000 nodes is 200000 stack frames. Iterative DFS with an explicit stack is the fix โ€” and a graded skill.

Recursion is a resource

Each frame costs stack; a linear chain of n nodes is n frames. The sandbox (like most judges) gives a few MB โ€” depth past ~1e5 dies. The fix: explicit stack, process (node, child-index) pairs, accumulate child answers before popping. Convert every n-deep recursion once and you will recognize it forever.