Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: List every root-to-leaf path whose values sum to the target.

Problem: List every root-to-leaf path whose values sum to the target.
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 paths(n, t, cur, out):
    if not n: return out
    cur.append(n.v)
    if not n.l and not n.r and sum(cur) == t: out.append(cur[:])
    paths(n.l, t, cur, out); paths(n.r, t, cur, out); cur.pop()
    return out
print(paths(build([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1]), 22, [], []))
What is printed?
  1. A. [[5, 4, 11, 2]]
  2. B. [[5, 4, 11, 2], [5, 8, 4, 5], [5, 8, 13]]
  3. C. [[5, 8, 4, 5]]
  4. D. [[5, 4, 11, 2], [5, 8, 4, 5]]

Correct answer: D. [[5, 4, 11, 2], [5, 8, 4, 5]]

Root-to-leaf sums: 5-4-11-7 = 27, 5-4-11-2 = 22 ✓, 5-8-13 = 26, 5-8-4-5 = 22 ✓, 5-8-4-1 = 18. Copying cur (cur[:]) is essential; appending the list itself would leave empty lists after the backtracking pops.

More Coding Interview Problems questions

Exams that ask this topic