Recursion depth and when to walk a tree iteratively

Trees Junior Python 3.13+ Reviewed By Best Latest Apps

Predict the output

What does this print?

Python 3.13
import sys
print(sys.getrecursionlimit())

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 1000

Right: CPython's default recursion limit is 1000.

A chain-shaped tree deeper than the limit makes recursive walks fail, which is when an explicit stack helps.

Why not the others?
  • B 10000. That is a common value people set by hand, not the default.
  • C Unlimited. CPython caps recursion to avoid crashing the C stack.

30-second answer

Recursion uses one stack frame per level, so its depth equals the tree's height. On balanced trees that is about log₂ n, tiny even for millions of nodes. On a chain-shaped tree it is n, and CPython stops at about 1000 frames by default. Use an explicit stack (DFS) or queue (BFS) when the height can be large.

Practise saying it · 30 s. No recording, just a timer

Explain when to avoid recursion on trees.

Say your answer out loud, then check which of these points you covered:

  • Depth equals height
  • Default limit about 1000
  • Explicit stack or queue

Deep dive

Interviewers usually accept recursion; mention the depth limit and offer the iterative version.

Iterative in-order needs the 'go left, pop, go right' loop; pre-order is the easiest to convert.

Kotlin on the JVM has a deeper default stack, but very deep recursion still overflows.

Common mistakes

  • Raising sys.setrecursionlimit very high, which can crash CPython with a real stack overflow.
  • Assuming 'tree' means balanced.

Senior take & follow-ups

Ask whether the tree can be very deep. It shows you think about inputs, not just the happy path.

Follow-up questions

Think of your answer first, then open the hint.

  1. How deep can a search tree get?

    Show hint

    As deep as the number of keys if inserted in sorted order.

  2. Does tail-call optimisation help?

    Show hint

    Python and the JVM do not do it automatically; Kotlin's tailrec only works for self-calls in tail position.

What each operation costs: Binary Tree · Binary Search Tree · Tree Traversal

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.