Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: A tree of n nodes is stored as a skewed BST (keys inserted in increasing order). What is the cost of the recursive height function, and what is the risk in Python or Java when n = 10⁵?

  1. A. O(log n) time with no risk
  2. B. O(n) time, but recursion depth n can overflow the call stack – use an iterative BFS/DFS
  3. C. O(n²) time because each level recomputes the height
  4. D. O(n log n) time and O(1) stack

Correct answer: B. O(n) time, but recursion depth n can overflow the call stack – use an iterative BFS/DFS

Height visits each node once (O(n)), but on a skewed tree the recursion is n deep. Python's default limit is about 1000 frames and Java threads commonly overflow around 10⁴–10⁵ frames, so a level-order count of levels is safer. O(log n) depth only holds for balanced trees.

More Coding Interview Problems questions

Exams that ask this topic