Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

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 level-order list where index i has children 2i+1 and 2i+2 (None = no node).

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 level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
    def __init__(self, v, l=None, r=None):
        self.v, self.l, self.r = v, l, r
def build(xs, i=0):
    if i >= len(xs) or xs[i] is None: return None
    return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
def bad(t):
    if not t: return 0
    return 1 + min(bad(t.l), bad(t.r))
def good(t):
    if not t: return 0
    if not t.l: return 1 + good(t.r)
    if not t.r: return 1 + good(t.l)
    return 1 + min(good(t.l), good(t.r))
r = build([1, 2, None, 3, 4])
print(bad(r), good(r))
What is printed?
  1. A. 2 3
  2. B. 1 2
  3. C. 1 3
  4. D. 3 3

Correct answer: C. 1 3

The root has no right child, but an empty side is not a leaf. The buggy version takes min(…, 0) and reports depth 1. The correct version only uses a missing side when both are missing (a real leaf): root → 2 → 3 = 3. BFS that stops at the first leaf is also O(n) and often faster.

More Coding Interview Problems questions

Exams that ask this topic