Every DFS solution I have seen so far in LeetCode is recursive. I'm wondering why given that:
- there are recursion limits in almost every language (# of stack frames in the call stack) so recursive DFS on large graphs doesn't scale (heap size >> stack size, and e.g. Python does not do tail call optimization)
- iterative DFS requires requires using stacks in a manner that is not completely trivial, e.g. nodes can go from "undiscovered", to "being visited", to "finished".
- interviewers would naturally be intereted in your command of stacks and implementations that can scale better.
I haven't seen an iterative (e.g. Python) efficient implementation of DFS where successors pass data to ancestors (e.g. required for the DFS solution for this problem https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) and that use properly a stack (e.g. deque).
Why? And by the way, if you know of any please post it!