Bird
Raised Fist0

Examine the following buggy code for the Path Sum problem. Which line contains the subtle bug that causes incorrect results on some inputs?

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Path Sum
Examine the following buggy code for the Path Sum problem. Which line contains the subtle bug that causes incorrect results on some inputs?
def hasPathSum(root: Optional[TreeNode], targetSum: int) -> bool:
    def dfs(node, curr_sum):
        if not node:
            return False
        curr_sum += node.val
        if curr_sum == targetSum:  # Bug here
            return True
        return dfs(node.left, curr_sum) or dfs(node.right, curr_sum)
    return dfs(root, 0)
ALine 3: if not node: return False
BLine 6: if curr_sum == targetSum:
CLine 8: return dfs(node.left, curr_sum) or dfs(node.right, curr_sum)
DLine 5: curr_sum += node.val
Step-by-Step Solution
  1. Step 1: Understand leaf node condition

    The sum should be checked only at leaf nodes, not at every node.
  2. Step 2: Identify the bug

    Line 6 checks sum at any node, causing premature True returns for partial paths.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Bug causes incorrect True if partial path sum equals targetSum [OK]
Quick Trick: Sum check must be at leaf nodes only [OK]
Common Mistakes:
MISTAKES
  • Checking sum at internal nodes
  • Not handling null root
Trap Explanation:
PITFALL
  • Checking sum too early looks correct but breaks correctness on partial paths.
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle logic errors in recursion base cases.
Master "Path Sum" 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