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⁵?
- A. O(log n) time with no risk
- B. O(n) time, but recursion depth n can overflow the call stack – use an iterative BFS/DFS
- C. O(n²) time because each level recomputes the height
- 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
- Problem: Check whether two trees are mirror images of each other (here: whether a tree is symmetric). Trees are built by build(xs): a…
- Problem: Return the vertical sum of a tree for every column, left to right (root column 0, left child −1, right child +1). Trees are built…
- Problem: Find the minimum depth (nodes on the shortest root-to-LEAF path). The candidate below is buggy. Trees are built by build(xs): a…
- Problem: Insert keys into an empty BST in the given order and report the preorder traversal. python def insert(t, k): if t is None: return…
- Problem: Delete key 50 (a node with two children) from the BST built by inserting 50, 30, 70, 60, 80, 65 – replacing it with its inorder…
- Problem: Given the root of a BST with n nodes and a target, return the value closest to the target. What is the best time complexity…