Path 5->4->11->2 sums to 22, so the method returns true.
Final Answer:
true -> Option B
Quick Check:
Path sum 22 exists = true [OK]
Hint: Sum each root-to-leaf path to find target [OK]
Common Mistakes:
Ignoring leaf node condition
Summing partial paths not ending at leaf
Miscomputing sums of nodes
4. The following C# code attempts to check path sum but has a bug. What is the error?
public bool HasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null) return root.val == targetSum;
return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val);
}
medium
A. No bug; code works correctly
B. Should check for null root after subtracting value
C. Incorrect base case for leaf node check
D. Missing return statement in recursive calls
Solution
Step 1: Analyze base cases and recursion
Code returns false if root is null, correctly handles leaf node by comparing value to targetSum, and recursively checks left and right subtrees with updated targetSum.
Step 2: Confirm correctness of logic
All conditions and recursive calls are correct and return statements are present.
Final Answer:
No bug; code works correctly -> Option A
Quick Check:
Code logic matches problem requirements = No bug; code works correctly [OK]
Hint: Check base cases and recursive returns carefully [OK]
Common Mistakes:
Forgetting to subtract node value from targetSum
Missing return keyword in recursion
Incorrect leaf node condition
5. You want to find all root-to-leaf paths in a binary tree where the sum of node values equals a target sum. Which approach best extends the path sum check to collect all such paths?
hard
A. Sum all nodes and compare to target sum once traversal ends
B. Use BFS and stop at first path matching the sum
C. Use recursion without tracking path, just return true/false
D. Use DFS with a list to track current path and add to result when sum matches at leaf
Solution
Step 1: Understand the requirement to collect all paths
We need to find all root-to-leaf paths with sum equal to target, so we must track the current path during traversal.
Step 2: Choose the correct traversal and tracking method
DFS with a list to store nodes along the current path allows backtracking and collecting all valid paths when leaf and sum conditions are met.
Final Answer:
Use DFS with a list to track current path and add to result when sum matches at leaf -> Option D
Quick Check:
Track paths with DFS and list = Use DFS with a list to track current path and add to result when sum matches at leaf [OK]
Hint: Track path nodes during DFS to collect all valid paths [OK]
Common Mistakes:
Using BFS which is less natural for path tracking
Not tracking path nodes, only sums
Stopping at first found path instead of all
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.