ProgrammingHardAmazon OA · Flipkart coding round

Which change removes the RecursionError for a DFS over a path of 10^5 nodes, while keeping the same visiting order?

  1. A. Change the recursion limit to 10^9 and nothing else
  2. B. Call the DFS function inside a try block and restart from the root on failure
  3. C. Replace the list of children with a set so nodes are visited once
  4. D. Use an explicit stack and push children in reverse order so the first child is visited first

Correct answer: D. Use an explicit stack and push children in reverse order so the first child is visited first

An explicit stack keeps the state on the heap and avoids the frame limit. Pushing children in reverse keeps the same preorder as the recursive version.

More Python Programming questions

Exams that ask this topic