Given the
Output: true
Explanation: The path 5 → 4 → 11 → 2 sums to 22.
Output: false
Explanation: Available paths: 1→2 (sum 3) and 1→3 (sum 4). Neither equals 5.
Constraints:
0 <= Number of nodes <= 5000 -1000 <= Node.val <= 1000 -1000 <= targetSum <= 1000
Contents
Solution — Recursive DFS (Subtraction) Complexity Analysis
Instead of accumulating a running sum, we subtract each node's value from the target as we descend. At a leaf node, if the remaining value equals the leaf's value (i.e., the remainder after subtraction is 0 at that leaf), we found a valid path.
Algorithm:
- Base case: if
root == null , return false. - At each node, subtract the node's value from
targetSum . - If the node is a leaf and the remaining sum is 0, return true.
- Recurse on left and right subtrees; return true if either returns true.
Trace through Example 1: targetSum = 22, path 5→4→11→2
| Node | targetSum after subtraction |
|---|---|
| 5 | 22 - 5 = 17 |
| 4 | 17 - 4 = 13 |
| 11 | 13 - 11 = 2 |
| 2 (leaf) | 2 - 2 = 0 → return true |
- Time: O(n) — in the worst case every node is visited.
- Space: O(h) — recursion stack depth equals the tree height h.