Question presented to candidate: "Given the root of a binary tree and an integer target, write a Python function that returns True if some path from the root down to a leaf has values adding up to exactly the target. Then tell me how you would return all such paths."
What a strong answer should cover:
- Carry the remaining target down: subtract the node's value, and at a leaf check that the remainder is 0.
- A leaf has no children; a one-child node is not a leaf, so
[1, 2]with target 1 is False. - O(n) time, O(h) space; the short-circuit
orstops at the first valid path; negative values mean no pruning. - Follow-up: all paths with backtracking (append, recurse, pop) and a copy at each match.
- Python specifics: ints never overflow; store
list(path)(a copy) or every stored path is the same list that later gets emptied; the recursion limit of 1000 suggests an iterative(node, remaining)stack for deep trees.
Clarifying questions expected:
- "Must the path end at a leaf, and start at the root?"
- "Can the values or the target be negative?"
Code / implementation expected: Yes โ a short recursive Python function; optionally the iterative stack and the all-paths version.