Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Lowest common ancestor in a general binary tree (not a BST), with the recursive 'return whichever side found something' method.

Problem: Lowest common ancestor in a general binary tree (not a BST), with the recursive 'return whichever side found something' method.
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 lca(nd, p, q):
    if not nd or nd.v in (p, q): return nd
    l, r = lca(nd.l, p, q), lca(nd.r, p, q)
    return nd if l and r else l or r
root = build([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4])
print(lca(root, 7, 8).v, lca(root, 7, 6).v, lca(root, 5, 4).v)
What is printed?
  1. A. 5 5 2
  2. B. 3 2 5
  3. C. 3 5 5
  4. D. 1 5 5

Correct answer: C. 3 5 5

7 is under 5 (via 2) and 8 is under 1, so they meet at the root 3. 7 and 6 are both under 5. For 5 and 4, the search returns 5 as soon as it reaches it, because 4 lies inside 5's subtree, so 5 is its own LCA.

More Coding Interview Problems questions

Exams that ask this topic