
Problem
Solution
Submissions
Path Sum II
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C program to find all root-to-leaf paths in a binary tree where each path's sum equals a given target sum. A leaf is a node with no children. Return all the valid paths as a list of lists, where each inner list represents one valid path from root to leaf.
Example 1
- Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
- Output: [[5,4,11,2],[5,8,4,5]]
- Explanation:
- Path 1: 5 -> 4 -> 11 -> 2, Sum = 5+4+11+2 = 22.
- Path 2: 5 -> 8 -> 4 -> 5, Sum = 5+8+4+5 = 22.
- Both paths sum to the target value 22.
- These are the only two valid root-to-leaf paths.
- Path 1: 5 -> 4 -> 11 -> 2, Sum = 5+4+11+2 = 22.
Example 2
- Input: root = [1,2,3], targetSum = 5
- Output: []
- Explanation:
- Path 1: 1 -> 2, Sum = 1+2 = 3 (not equal to 5).
- Path 2: 1 -> 3, Sum = 1+3 = 4 (not equal to 5).
- No path sums to the target value 5.
- Therefore, return empty result.
- Path 1: 1 -> 2, Sum = 1+2 = 3 (not equal to 5).
Constraints
- The number of nodes in the tree is in the range [0, 5000]
- -1000 ≤ Node.val ≤ 1000
- -1000 ≤ targetSum ≤ 1000
- Time Complexity: O(n^2) where n is number of nodes
- Space Complexity: O(n) for recursion stack
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use depth-first search (DFS) to traverse all paths from root to leaves
- Maintain a current path array to track the nodes in the current path
- Keep track of the current sum as you traverse down the tree
- When you reach a leaf node, check if the current sum equals target sum
- If the sum matches, add a copy of the current path to the result
- Use backtracking to remove the current node when returning from recursion