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

Problem: Check whether a binary tree is a valid BST. The candidate solution compares each node only with its children. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).

Problem: Check whether a binary tree is a valid BST. The candidate solution compares each node only with its children. 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 naive(t):
    if not t: return True
    if t.l and t.l.v >= t.v: return False
    if t.r and t.r.v <= t.v: return False
    return naive(t.l) and naive(t.r)
def correct(t, lo=float('-inf'), hi=float('inf')):
    if not t: return True
    if not (lo < t.v < hi): return False
    return correct(t.l, lo, t.v) and correct(t.r, t.v, hi)
r = build([10, 5, 15, None, None, 6, 20])
print(naive(r), correct(r))
What is printed?
  1. A. True True
  2. B. False False
  3. C. False True
  4. D. True False

Correct answer: D. True False

Node 6 is the left child of 15 (fine locally) but sits in the right subtree of 10, so it must exceed 10. Passing (low, high) bounds down catches this; the child-only check does not. O(n).

More Coding Interview Problems questions

Exams that ask this topic