Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Count root-to-leaf paths whose values sum to a target. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
Problem: Count root-to-leaf paths whose values sum to a target. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
def __init__(self, v, l=None, r=None):
self.v, self.l, self.r = v, l, r
def build(xs, i=0):
if i >= len(xs) or xs[i] is None: return None
return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
def count_paths(t, target):
if not t: return 0
target -= t.v
if not t.l and not t.r:
return 1 if target == 0 else 0
return count_paths(t.l, target) + count_paths(t.r, target)
print(count_paths(build([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, None, 5, 1]), 22))What is printed?- A. 3
- B. 1
- C. 2
- D. 0
Correct answer: C. 2
Root-to-leaf sums: 5+4+11+7 = 27, 5+4+11+2 = 22 ✓, 5+8+13 = 26, 5+8+4+5 = 22 ✓, 5+8+4+1 = 18. Two paths. Checking the sum at None children instead of at leaves would double-count each leaf. O(n).
More Coding Interview Problems questions
- Problem: Count downward paths (starting anywhere, ending anywhere below) that sum to k, using prefix sums on the root-to-node path. Trees…
- Problem: Serialize a tree in preorder with '#' for missing children, then count the nodes from the string alone. python class T: def…
- Problem: Rebuild a tree from its preorder and inorder sequences (distinct values) and print its postorder. python def post(pre, ino): if…
- Problem: Check whether a tree is height-balanced (every node's subtree heights differ by at most 1). Trees are built by build(xs): a…
- Problem: Return the zigzag level order (left→right, then right→left, alternating). Trees are built by build(xs): a level-order list where…
- Problem: Convert a sorted array into a height-balanced BST and print its preorder. python def pre(a, lo, hi, out): if lo > hi: return out…