LeetCode 437. Path Sum III
š§© Problem Description
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the node values in the path equals targetSum.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
š¬ Example
Example 1
1 | Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 |
Example 2
1 | Input: root = [1], targetSum = 1 |
š” Approach 1: DFS (Brute Force)
The most straightforward solution is:
- For each node, start a DFS to find all downward paths whose sum equals
targetSum. - This results in O(n²) time complexity in the worst case.
š¢ Java Code (Brute Force)
1 | class Solution { |
š” Approach 2: Prefix Sum + HashMap (Optimized)
We can reduce time complexity to O(n) by:
- Maintaining a prefix sum map that stores
(currentSum ā frequency). - At each node, we calculate how many previous prefix sums satisfy:
1
currentSum - targetSum = somePreviousPrefix
- Update the map during DFS and backtrack after visiting children.
š¢ Java Code (Optimized)
1 | class Solution { |
ā± Time and Space Complexity
Brute Force
- Time: O(n²) in worst case
- Space: O(h) recursion stack
Prefix Sum Optimized
- Time: O(n) ā visiting each node once
- Space: O(n) ā prefix sum map and recursion stack
āļø Summary
- Brute Force: Try all starting points ā simple but slow.
- Prefix Sum: Tracks how many ways we can reach
targetSumefficiently. - Related problems:
lc-112ā Path Sumlc-113ā Path Sum IIlc-437ā Path Sum III (this one)