Get the latest tech news
Iterative DFS with stack-based graph traversal (2024)
This post explores how to effectively implement an iterative depth-first search (DFS) traversal on a graph with a stack, addressing a common pitfall along the way.
Depth-first search (DFS) on a graph (binary tree or otherwise) is most often implemented recursively, but there are occasions where it may be desirable to consider an iterative approach instead. Specifically, as noted in another blog post, it is easy to fall into the trap of using a stack haphazardly and conducting a graph search that is not truly DFS. As also mentioned in the blog post, both approaches above have the property that replacing the stack by a queue gives a breadth-first search, albeit implemented in a somewhat nonstandard way.
Or read this on Hacker News