Bird
Raised Fist0

Examine the following snippet from a House Robber III solution: ```python def dfs(node): if not node: return (0, 0) left = dfs(node.left) right = dfs(node.right...

medium🐞 Bug Q7 of Q15
Tree: Depth-First Search - House Robber III (On Tree)
Examine the following snippet from a House Robber III solution: ```python def dfs(node): if not node: return (0, 0) left = dfs(node.left) right = dfs(node.right) rob_current = node.val + left[0] + right[0] not_rob_current = max(left) + max(right) return (not_rob_current, rob_current) ``` Identify the subtle bug causing incorrect results.
ASwapping the order of returned tuple values causes confusion in parent calls
BUsing max(left) and max(right) instead of specific indices is incorrect
CAdding left[0] and right[0] to rob_current should be left[1] and right[1]
DReturning a tuple instead of a single integer causes type errors
Step-by-Step Solution
Solution:
  1. Step 1: Understand returned tuple meaning

    Conventionally, dfs returns (rob_current, not_rob_current) consistently.
  2. Step 2: Check return order

    This code returns (not_rob_current, rob_current), which is opposite of what callers expect.
  3. Step 3: Consequence

    Parent calls interpret values incorrectly, leading to wrong sums.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Are return values consistent with usage? No. [OK]
Quick Trick: Return tuple order must match usage consistently [OK]
Common Mistakes:
MISTAKES
  • Mixing up tuple order of rob/not_rob values
  • Using max() on tuples instead of indices
  • Incorrectly summing child states
Trap Explanation:
PITFALL
  • Swapping tuple order looks harmless but breaks recursive logic.
Interviewer Note:
CONTEXT
  • Tests attention to detail in recursive state management.
Master "House Robber III (On Tree)" 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