Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Sum the values of all LEFT leaves (leaves that are the left child of their parent). Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.

Problem: Sum the values of all LEFT leaves (leaves that are the left child of their parent). 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 left_leaves(t, is_left=False):
    if not t: return 0
    if not t.l and not t.r: return t.v if is_left else 0
    return left_leaves(t.l, True) + left_leaves(t.r, False)
print(left_leaves(build([6, 2, 9, 1, 4, 7, 5, None, None, 3])))
What is printed?
  1. A. 16
  2. B. 8
  3. C. 11
  4. D. 14

Correct answer: C. 11

The tree: 6 → (2, 9); 2 → (1, 4); 9 → (7, 5); 4 → (3, –). Leaves are 1, 3, 7 and 5; 1, 3 and 7 are left children (of 2, 4 and 9) but 5 is a right child → 11. Summing every leaf gives 16, and 14 wrongly counts the internal node 4 instead of the leaf 1. A lone root is not a left leaf, which is why the flag starts False. O(n).

More Coding Interview Problems questions

Exams that ask this topic