Path Sum III - Problem

You're given the root of a binary tree and an integer targetSum. Your mission is to find the total number of downward paths in the tree where the sum of node values equals the target sum.

Here's the twist: paths don't need to start at the root or end at a leaf! Any downward path (parent to child) that sums to the target counts. Think of it like finding all the "treasure paths" in a tree where each path's gold coins add up to exactly your target amount.

Example: In a tree with nodes [10,5,-3,3,2,null,11,3,-2,null,1], if targetSum = 8, you might find paths like [5,3], [5,2,1], or even [-3,11] that all sum to 8.

Goal: Return the count of all valid downward paths that sum to targetSum.

Input & Output

example_1.py โ€” Standard Tree
$ Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
โ€บ Output: 3
๐Ÿ’ก Note: The paths that sum to 8 are: [5,3], [5,2,1], and [-3,11]. Note how these paths can start and end at any nodes as long as they go downward.
example_2.py โ€” Simple Path
$ Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
โ€บ Output: 3
๐Ÿ’ก Note: The paths that sum to 22 are: [5,4,11,2], [5,8,4,5], and [4,11,7]. Multiple valid downward paths exist in this tree.
example_3.py โ€” Edge Case
$ Input: root = [1], targetSum = 1
โ€บ Output: 1
๐Ÿ’ก Note: Single node tree where the root itself equals the target sum, so there's exactly one valid path.

Visualization

Tap to expand
StartCheckpointValid Trail!EndGPS MemoryElevation 0: โœ“Elevation 10: โœ“Elevation 15: โœ“Target Change: 8Trail Counter๐Ÿฅพ Trail 1: Found!๐Ÿฅพ Trail 2: Found!๐Ÿฅพ Trail 3: Found!Total: 3 trails
Understanding the Visualization
1
Start hiking with GPS
Begin DFS traversal while GPS tracks cumulative elevation (prefix sum)
2
Check for trail segments
At each point, GPS checks if any previous checkpoint creates valid trail to current position
3
Record and backtrack
Count valid trails, update GPS with current position, then remove it when backtracking
Key Takeaway
๐ŸŽฏ Key Insight: Prefix sum + HashMap transforms O(nยฒ) brute force into O(n) optimal solution by remembering path sums and using mathematical relationships

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Visit each node exactly once during DFS traversal

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

HashMap can store up to O(n) prefix sums in worst case, plus O(h) recursion stack

n
2n
โšก Linearithmic Space

Constraints

  • The number of nodes in the tree is in the range [0, 1000]
  • Each node value is in range [-109, 109]
  • targetSum is in range [-1000, 1000]
  • Path must go downward (parent to child direction only)
Asked in
Amazon 45 Facebook 38 Microsoft 32 Google 28 Apple 22
425.0K 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