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?- A. 702
- B. 671
- C. 1012
- 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
- 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…
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Count good nodes. Trees are built from a…
- Problem: Exactly two keys of a BST were swapped by mistake. Find them with an inorder traversal: the first key is the left side of the…