Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Each root-to-leaf path spells a number (digits from root to leaf). Return the sum of these numbers. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.

Problem: Each root-to-leaf path spells a number (digits from root to leaf). Return the sum of these numbers. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
from collections import deque
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):  # level order, None = missing child
    root = T(xs[0]); q = deque([root]); i = 1
    while i < len(xs):
        node = q.popleft()
        for side in ("l", "r"):
            if i < len(xs) and xs[i] is not None:
                setattr(node, side, T(xs[i])); q.append(getattr(node, side))
            i += 1
    return root
def leaf_numbers(t, cur=0):
    if not t: return 0
    cur = cur * 10 + t.v
    if not t.l and not t.r: return cur
    return leaf_numbers(t.l, cur) + leaf_numbers(t.r, cur)
print(leaf_numbers(build([3, 1, 5, 9, None, 2, 0])))
What is printed?
  1. A. 702
  2. B. 671
  3. C. 1012
  4. D. 1021

Correct answer: D. 1021

Paths: 3 → 1 → 9 = 319, 3 → 5 → 2 = 352, 3 → 5 → 0 = 350; 319 + 352 + 350 = 1021. The node 1 has only a left child, so it is not a leaf and 31 is not counted. Building the number as cur·10 + digit on the way down avoids string concatenation. O(n).

More Coding Interview Problems questions

Exams that ask this topic