Path Sum III - Problem

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

A path can start from any node and end at any descendant of that node, as long as the direction is always downward.

Input & Output

Example 1 — Basic Tree
$ Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
💡 Note: Three paths sum to 8: (5→3), (5→2→1), and (-3→11)
Example 2 — Simple Tree
$ Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: 3
💡 Note: Paths: (5→4→11→2), (5→8→4→5), and (4→11→7)
Example 3 — Single Node
$ Input: root = [1], targetSum = 1
Output: 1
💡 Note: Only one node with value 1, which equals targetSum

Constraints

  • The number of nodes in the tree is in the range [0, 1000]
  • -109 ≤ Node.val ≤ 109
  • -1000 ≤ targetSum ≤ 1000

Visualization

Tap to expand
Path Sum III - Hash Map Approach INPUT Binary Tree Structure 10 5 -3 3 2 11 3 -2 1 root = [10,5,-3,3,2, null,11,3,-2,null,1] targetSum = 8 Find paths summing to 8 ALGORITHM STEPS 1 Initialize Hash Map prefixSum map with {0: 1} 2 DFS Traversal Track running sum at each node 3 Check Complement Find (currSum - target) in map 4 Update and Backtrack Add sum to map, remove on return Prefix Sum Hash Map Prefix Sum Count 0 1 (initial) 10 1 15 1 7 1 currSum - target found in map = valid path FINAL RESULT 3 Valid Paths Found: Path 1: 5 --> 3 Sum: 5 + 3 = 8 [OK] OK Path 2: 5 --> 2 --> 1 Sum: 5 + 2 + 1 = 8 [OK] OK Path 3: -3 --> 11 Sum: -3 + 11 = 8 [OK] OK Output: 3 Time: O(n) Space: O(h) - tree height Each node visited once Key Insight: Prefix Sum with Hash Map The hash map stores prefix sums encountered along the path. At each node, if (currentSum - targetSum) exists in the map, it means there's a valid path ending at current node. The map count tells how many such paths exist. Backtracking removes the sum when leaving a node to avoid counting paths across branches. TutorialsPoint - Path Sum III | Hash Map Approach
Asked in
Amazon 45 Google 35 Facebook 28 Microsoft 22
316.1K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen