Data Structures & AlgorithmsHardAmazon · Microsoft OA

Find the bug: this BST validator compares each node only with its own children.

Find the bug: this BST validator compares each node only with its own children.
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):
    nodes = [T(x) if x is not None else None for x in xs]
    kids = iter(nodes[1:])
    for nd in nodes:
        if nd:
            nd.l = next(kids, None); nd.r = next(kids, None)
    return nodes[0]
def valid(nd):
    if not nd: return True
    if nd.l and nd.l.v >= nd.v: return False
    if nd.r and nd.r.v <= nd.v: return False
    return valid(nd.l) and valid(nd.r)
print(valid(build([10, 5, 15, None, None, 6, 20])))
What is printed?
  1. A. True
  2. B. False
  3. C. None
  4. D. It raises an AttributeError

Correct answer: A. True

Every parent–child pair is ordered, so it prints True, but 6 sits in the right subtree of 10 and violates the BST property. A correct check passes down (low, high) bounds, or verifies that the inorder traversal is strictly increasing.

More Coding Interview Problems questions

Exams that ask this topic