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?- A. 16
- B. 8
- C. 11
- 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
- Problem: Return (level, sum) of the level with the largest sum, levels numbered from 1 (smallest level on ties). Trees are built from a…
- 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…
- Problem: Split a string into pieces that are all palindromes and list every such partition (backtracking). python def palparts(s): res =…
- Problem: Find all combinations of unlimited-use stamp values that total exactly 15 (each combination listed once, in non-decreasing…
- Problem: Restore all valid IPv4 addresses from a digit string (four parts, each 0–255, no leading zeros except "0"). python def…
- Problem: Return every value an arithmetic expression can take under all possible full parenthesisations (divide and conquer on each…