Bird
Raised Fist0

Given the tree below and targetSum = 7, what is the final returned list?

easy🧾 Code Trace Q12 of Q15
Tree: Depth-First Search - Path Sum II (All Root-to-Leaf Paths)
Consider the following iterative DFS code for finding all root-to-leaf paths with a given sum. Given the tree below and targetSum = 7, what is the final returned list? Tree structure: 5 / \ 4 8 / / \ 11 13 4 Target sum: 7
def pathSum(root, targetSum):
    if not root:
        return []
    res = []
    stack = [(root, [root.val], root.val)]
    while stack:
        node, path, current_sum = stack.pop()
        if not node.left and not node.right:
            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
A[]
B[[5, 4, 11]]
C[[5, 4]]
D[[5, 8, 4]]
Step-by-Step Solution
Solution:
  1. Step 1: Trace paths and sums

    Paths: 5->4->11 sum=20, 5->8->13 sum=26, 5->8->4 sum=17; none equals 7.
  2. Step 2: Confirm no leaf path sums to 7

    Since no leaf path sums to 7, result list remains empty.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    No leaf path sums to 7, so empty list returned [OK]
Quick Trick: Check sums only at leaf nodes [OK]
Common Mistakes:
MISTAKES
  • Confusing intermediate node sums with leaf sums
  • Forgetting to check leaf condition
Trap Explanation:
PITFALL
  • Candidates often forget to check leaf nodes only, leading to wrong paths included
Interviewer Note:
CONTEXT
  • Tests ability to trace iterative DFS and understand leaf condition
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