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.
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.
Time & Space Complexity
Time Complexity
O(n)
We visit each node once. In worst case, we might need to copy O(n) paths, each of length O(log n) to O(n)
β Linear Growth
Space Complexity
O(h)
Recursion depth is limited by tree height h. Additional space for storing result paths
β Linear Space
Constraints
- The number of nodes in the tree is in the range [0, 5000]
- β1000 β€ Node.val β€ 1000
- β1000 β€ targetSum β€ 1000
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code