Repaso
Español
Algorithms & DSAdvancedALG-24

Space complexity of recursive DFS on a binary tree of height h?

Options

  1. O(1), since no extra memory is allocated
  2. O(h) for the recursion call stack (Correct option)
  3. O(n²), since each node is visited twice
  4. O(log h) for the depth of the call stack

Answer

O(h) for the call stack

Why

Recursive DFS keeps one call-stack frame for each node on the current path from the root. The longest path has h nodes, so memory is O(h).

For a balanced tree h ≈ log n; for a completely skewed tree h = n.

BFS instead keeps a whole level in its queue: O(width).

Remember

Recursion memory = depth of the recursion.

Key terms

Practice this question in Repaso