Bird
Raised Fist0

Examine the following buggy code snippet for summing root-to-leaf numbers using DFS recursion. Which line contains the subtle bug causing incorrect sums on some inputs?

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Sum Root to Leaf Numbers
Examine the following buggy code snippet for summing root-to-leaf numbers using DFS recursion. Which line contains the subtle bug causing incorrect sums on some inputs?
class Solution:
    def sumNumbers(self, root: TreeNode) -> int:
        self.total = 0
        def dfs(node, current_number):
            if not node:
                return
            current_number = current_number * 10 + node.val
            self.total += current_number  # Bug here
            if not node.left and not node.right:
                return
            dfs(node.left, current_number)
            dfs(node.right, current_number)
        dfs(root, 0)
        return self.total
ALine with 'if not node:' return statement
BLine adding current_number to self.total
CLine checking if node is leaf
DLine calling dfs on node.right
Step-by-Step Solution
  1. Step 1: Understand when sums should be added

    Sum should only include complete root-to-leaf numbers, so addition must happen only at leaf nodes.
  2. Step 2: Identify incorrect addition

    Adding current_number at every node (including non-leaf) causes partial numbers to be summed, inflating total incorrectly.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Sum only at leaves fixes the bug [OK]
Quick Trick: Add to total only at leaf nodes [OK]
Common Mistakes:
MISTAKES
  • Adding partial path sums at non-leaf nodes
  • Not resetting total between calls
Trap Explanation:
PITFALL
  • Adding current_number too early looks plausible but breaks correctness on non-leaf nodes.
Interviewer Note:
CONTEXT
  • Checks if candidate can spot subtle logic errors in recursive accumulation.
Master "Sum Root to Leaf Numbers" 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