Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Count root-to-leaf paths whose values sum to a target. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).

Problem: Count root-to-leaf paths whose values sum to a target. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
    def __init__(self, v, l=None, r=None):
        self.v, self.l, self.r = v, l, r
def build(xs, i=0):
    if i >= len(xs) or xs[i] is None: return None
    return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
def count_paths(t, target):
    if not t: return 0
    target -= t.v
    if not t.l and not t.r:
        return 1 if target == 0 else 0
    return count_paths(t.l, target) + count_paths(t.r, target)
print(count_paths(build([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, None, 5, 1]), 22))
What is printed?
  1. A. 3
  2. B. 1
  3. C. 2
  4. D. 0

Correct answer: C. 2

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. Two paths. Checking the sum at None children instead of at leaves would double-count each leaf. O(n).

More Coding Interview Problems questions

Exams that ask this topic