Bird
Raised Fist0

Examine the following buggy iterative DFS code for finding all root-to-leaf paths with a given sum. Which line contains the subtle bug that causes incorrect results?

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Path Sum II (All Root-to-Leaf Paths)
Examine the following buggy iterative DFS code for finding all root-to-leaf paths with a given sum. Which line contains the subtle bug that causes incorrect results?
def pathSum(root, targetSum):
    if not root:
        return []
    res = []
    stack = [(root, [root.val], root.val)]
    while stack:
        node, path, current_sum = stack.pop()
        if current_sum == targetSum:
            res.append(path)
        if node.right:
            stack.append((node.right, path + [node.right.val], current_sum + node.right.val))
        if node.left:
            stack.append((node.left, path + [node.left.val], current_sum + node.left.val))
    return res
ALine appending left child to stack
BLine initializing stack with root node and path
CLine appending right child to stack
DLine checking if current_sum == targetSum without verifying leaf node
Step-by-Step Solution
Solution:
  1. Step 1: Identify condition for adding path to results

    Correct code adds path only if current node is leaf and sum matches.
  2. Step 2: Locate bug

    Here, path is added whenever sum matches, regardless of leaf status, causing incomplete paths to be included.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Missing leaf check causes incorrect paths in results [OK]
Quick Trick: Always check leaf node before adding path [OK]
Common Mistakes:
MISTAKES
  • Adding path before confirming leaf node
  • Forgetting to backtrack in recursion
Trap Explanation:
PITFALL
  • Sum check alone looks correct but misses leaf condition, a subtle bug
Interviewer Note:
CONTEXT
  • Tests attention to subtle correctness conditions in DFS path problems
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