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?- A. [[5, 4, 11, 2]]
- B. [[5, 4, 11, 2], [5, 8, 4, 5], [5, 8, 13]]
- C. [[5, 8, 4, 5]]
- 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
- Problem: Count the BST keys within [lo, hi], pruning subtrees that cannot contain answers. python class T: def init(s, v): s.v, s.l, s.r =…
- Problem: Delete a node with two children from a BST by replacing it with its inorder successor; print the preorder afterwards. python…
- Problem: Insert keys into an AVL tree (rebalancing with rotations) and print the root and the tree height (a single node has height 1)…
- Problem: Ackermann's function grows faster than any primitive-recursive function. Compute A(2, 3) and count the recursive calls. python…
- Problem: Count the calls made by naive recursive Fibonacci versus a memoised version for n = 10. python from functools import lrucache…
- What is the time complexity of this loop? python for i in range(1, n + 1): j = 1 while j j <= i: j += 1