Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Find the maximum |a − b| where a is an ancestor of b in a binary tree.

Problem: Find the maximum |a − b| where a is an ancestor of b in a binary tree.
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 best(nd, lo, hi):
    if not nd: return hi - lo
    lo, hi = min(lo, nd.v), max(hi, nd.v)
    return max(best(nd.l, lo, hi), best(nd.r, lo, hi))
root = build([8, 3, 10, 1, 6, None, 14, None, None, 4, 7, 13])
print(best(root, root.v, root.v))
What is printed?
  1. A. 7
  2. B. 13
  3. C. 11
  4. D. 6

Correct answer: A. 7

Carry the min and max along each root-to-leaf path; the answer is the largest max − min. On the path 8 → 3 → 1 the spread is 8 − 1 = 7; on 8 → 10 → 14 → 13 it is 14 − 8 = 6. The best is 7. 13 = 14 − 1 pairs nodes on different branches, which are not ancestor-related.

More Coding Interview Problems questions

Exams that ask this topic