Yes, this traversal algorithm is correct and will visit all vertices in the connected component of the starting node v
. It’s a variation of DFS that marks nodes as visited when they are pushed onto the stack, rather than when they are popped, which avoids pushing the same node multiple times. This makes it more memory-efficient than standard iterative DFS, but it doesn't produce a post-order traversal (which is important for algorithms like topological sort or strongly connected components). Use this approach when you simply need to visit all reachable nodes efficiently without duplicates in the stack. Use standard DFS if you need post-order properties or more control over the traversal order.