Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Sum all LEFT leaves of a binary tree (leaves that are the left child of their parent).

Problem: Sum all LEFT leaves of a binary tree (leaves that are the left child of their parent).
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 sl(n, is_left=False):
    if not n: return 0
    if not n.l and not n.r: return n.v if is_left else 0
    return sl(n.l, True) + sl(n.r, False)
print(sl(build([3, 9, 20, None, 4, 15, 7, 6])))
What is printed?
  1. A. 21
  2. B. 30
  3. C. 15
  4. D. 34

Correct answer: A. 21

Tree: 3 → (9, 20); 9 → (−, 4); 20 → (15, 7); 4 → (6, −). Left leaves: 6 (left child of 4) and 15 (left child of 20) = 21. 9 is a left child but not a leaf; 4 is a right child.

More Coding Interview Problems questions

Exams that ask this topic