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?- A. True True
- B. False False
- C. False True
- 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
- Problem: Find the lowest common ancestor of two keys in a BST. Trees are built by build(xs): a level-order list where index i has children…
- Problem: Find the k-th smallest key in a BST. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2…
- Problem: Return the diameter of a tree – the number of edges on the longest path between any two nodes. Trees are built by build(xs): a…
- Problem: Find the maximum sum of any path in a tree (a path goes between any two nodes, need not pass through the root, values may be…
- Problem: Count root-to-leaf paths whose values sum to a target. Trees are built by build(xs): a level-order list where index i has…
- Problem: Count downward paths (starting anywhere, ending anywhere below) that sum to k, using prefix sums on the root-to-node path. Trees…