[1.7.x] switch out recursive dfs for stack based approach, to avoid possibly hitting the recursion limit