Introduction
Path Sum II means:
- finding all root-to-leaf paths
- whose total sum
equals target value
Goal:
- explore every path
- calculate path sum
- store valid paths
Example:
5/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Target:
22
Valid Paths: 5 → 4 → 11 → 2 5 → 8 → 4 → 5
Explanation:
Only root-to-leaf paths with target sum are stored.This problem is one of the most important applications of:
DFS Traversal Constraints
1 <= Number of Nodes <= 10^5 Approach : Recursive DFS + Backtracking Solution
Explanations:
Explanation:
The idea is:
- traverse tree using DFS
- maintain current path
- track remaining target sum
Steps:
- Visit current node.
- Add node into path.
- Subtract node value from target.
- Check leaf condition.
- Store valid path.
- Traverse child nodes.
- Backtrack path.
Leaf Condition:
left == null and right == nullTarget Condition:
remainingSum == node.value This approach:
- uses DFS recursion
- performs path tracking
- uses backtracking
Dry Run
Visit:5 Remaining target:
17
Visit:
4
Remaining target:
13
Visit:
11
Remaining target:
2
Visit:
2
Target matched.
Store path:
5 → 4 → 11 → 2
Practice :