Pick the fix
A chain-shaped tree of 5,000 nodes makes the recursive version crash in CPython. What is the best fix?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Walk it with a queue or an explicit stack instead
Right: the work stays O(n) and nothing depends on the call stack.
The default limit is 1000 frames, and an iterative walk removes that ceiling without changing the cost.
Why not the others?
- B Raise the recursion limit to 10**9. That can crash the interpreter itself when the real C stack overflows.
- C Memoise the depth function. Each node is visited once already; the problem is depth, not repeats.
Steps come from running the Python solution.
Text version
preorder:
Tree:
- 8
- 3 (left)
- 1 (left)
- 6 (right)
- 4 (left)
- 7 (right)
- 10 (right)
- 14 (right)
- 3 (left)
- Visit 8
- Visit 3
- Visit 1
- Visit 6
- Visit 4
- Visit 7
- Visit 10
- Visit 14
Result: 4. Order: 8, 3, 1, 6, 4, 7, 10, 14
level order:
Tree:
- 8
- 3 (left)
- 1 (left)
- 6 (right)
- 4 (left)
- 7 (right)
- 10 (right)
- 14 (right)
- 3 (left)
- Visit 8
- Visit 3
- Visit 10
- Visit 1
- Visit 6
- Visit 14
- Visit 4
- Visit 7
Result: 4. Order: 8, 3, 10, 1, 6, 14, 4, 7