Path Sum II - Problem
Path Sum II is a classic tree traversal problem that challenges you to find all root-to-leaf paths in a binary tree where the sum equals a target value.
🎯 Your Mission: Given a binary tree and a target sum, discover every possible path from root to leaf where the node values add up exactly to your target.
📋 What You're Given:
•
•
📤 What You Return:
• A list of lists, where each inner list contains the node values of a valid path
• Each path must start at the root and end at a leaf node
• The sum of values in each path must equal
🌳 Remember: A leaf node has no children, and you need the actual node values, not references!
🎯 Your Mission: Given a binary tree and a target sum, discover every possible path from root to leaf where the node values add up exactly to your target.
📋 What You're Given:
•
root - The root node of a binary tree•
targetSum - An integer representing your target sum📤 What You Return:
• A list of lists, where each inner list contains the node values of a valid path
• Each path must start at the root and end at a leaf node
• The sum of values in each path must equal
targetSum🌳 Remember: A leaf node has no children, and you need the actual node values, not references!
Input & Output
example_1.py — Basic Tree
$
Input:
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
›
Output:
[[5,4,11,2],[5,8,4,1]]
💡 Note:
There are two paths whose sum equals 22: 5+4+11+2=22 and 5+8+4+1=22. Both start from root and end at leaf nodes.
example_2.py — Single Node
$
Input:
root = [1,2,3], targetSum = 5
›
Output:
[]
💡 Note:
No root-to-leaf path sums to 5. The paths are [1,2] (sum=3) and [1,3] (sum=4).
example_3.py — Single Node Match
$
Input:
root = [1], targetSum = 1
›
Output:
[[1]]
💡 Note:
The only path is [1] which sums to 1, matching our target.
Constraints
- The number of nodes in the tree is in the range [0, 5000]
- −1000 ≤ Node.val ≤ 1000
- −1000 ≤ targetSum ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Start Journey
Begin at the mountain base (root) with full energy budget
2
Follow Trails
At each junction, spend energy (add node value) and choose a path
3
Reach Summit
When you reach a dead-end trail (leaf), check if energy spent equals budget
4
Backtrack
Return to previous junction to explore other trails
Key Takeaway
🎯 Key Insight: Backtracking allows us to explore all possible paths efficiently by building solutions incrementally and undoing choices when we need to try different alternatives.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code