Bird
Raised Fist0

Which line contains a subtle bug that causes incorrect results when multiple paths exist?

medium๐Ÿž Bug Identification Q7 of Q15
Tree: Depth-First Search - Path Sum II (All Root-to-Leaf Paths)
Examine the following recursive code snippet for Path Sum II. Which line contains a subtle bug that causes incorrect results when multiple paths exist? ```python def dfs(node, path, current_sum): if not node: return path.append(node.val) if not node.left and not node.right and current_sum + node.val == targetSum: res.append(path) dfs(node.left, path, current_sum + node.val) dfs(node.right, path, current_sum + node.val) path.pop() ```
AAppending path directly to results without copying
BNot checking if node is None before recursion
CNot updating current_sum correctly
DNot popping from path after recursion
Step-by-Step Solution
Solution:
  1. Step 1: Identify how path is stored

    Appending 'path' directly stores a reference, so all results share the same list object.
  2. Step 2: Consequence of shared reference

    Later modifications to 'path' affect all stored results, causing incorrect final output.
  3. Final Answer:

    Option A โ†’ Option A
  4. Quick Check:

    Must append a copy of path, not the path itself [OK]
Quick Trick: Always append a copy of path to results [OK]
Common Mistakes:
MISTAKES
  • Appending mutable path directly
  • Forgetting to pop after recursion
Trap Explanation:
PITFALL
  • Candidates miss that lists are mutable and shared references cause bugs.
Interviewer Note:
CONTEXT
  • Tests understanding of mutable state and backtracking correctness.
Master "Path Sum II (All Root-to-Leaf Paths)" in Tree: Depth-First Search

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions ยท All difficulty levels ยท Free

Free Signup - Practice All Questions
More Tree: Depth-First Search Quizzes