Home
DSA Patterns
Depth-First Search
Path Sum III
Path Sum III (LeetCode 437)
Path Sum III (LeetCode 437): count the downward paths in a binary tree that sum to a target. Keep the prefix sums of the current root-to-node path in a hash map and look up prefix − target at every node.
Problem Understanding
Path Sum III (LeetCode 437): given the root of a binary tree and an integer targetSum, return the number of paths whose values sum to targetSum. A path does not have to start at the root or end at a leaf, but it must go downward, from parent to child.
Examples: [10,5,-3,3,2,null,11,3,-2,null,1], target 8 → 3 (5 → 3, 5 → 2 → 1, -3 → 11); [5,4,8,11,null,13,4,7,2,null,null,5,1], target 22 → 3.
The Intuition: Subarray Sum Equals K, on a Root-to-Node Path
Any root-to-node path is just an array, and a downward path is a subarray of it. Subarray Sum Equals K counts subarrays with a given sum using prefix sums in a hash map; this is the same trick, run along every path of the tree.
- Seed the map with
count[0] = 1, so a path may start at the root. - At each node, add its value to the running
prefix. Every earlier prefix equal toprefix − targetstarts a path that ends here, so addcount[prefix − target]to the answer. Then recordprefix. - Recurse into both children with the new prefix.
- Backtrack: decrement
count[prefix]before returning, so the map only ever holds the current path.
Compare Path Sum and Path Sum II, where paths must run from the root to a leaf and a single running total is enough.
Path Sum III Visualization
TARGET 8 · p = PREFIX SUM FROM THE ROOT · GREEN = A PATH THAT SUMS TO THE TARGET
SEED count[0] = 1
prefix
:
look up
:
paths
0
count: prefix × times
count = {0: 1}: an empty prefix, so a path may start at the root. Target 8
Next
10: prefix 0 + 10 = 10. No prefix 2 on the path above, so no path ends here. Record 10
Tree
target
Nodes on the current path show p, their prefix sum, and the aside shows the hash map. At each node the figure looks up prefix − target; when it finds a match, the matching paths turn green. Watch the map shrink as the DFS backs out of a subtree. Try Negatives, where values cancel, and Zeros, where every path counts.
Path Sum III Dry Run
Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8. Nodes in visit order:
| Node | prefix | Look up prefix − 8 | Found | Total |
|---|---|---|---|---|
| 10 | 10 | 2 | 0 | 0 |
| 5 | 15 | 7 | 0 | 0 |
| 3 | 18 | 10 | 1 (5 → 3) | 1 |
| 3 | 21 | 13 | 0 | 1 |
| -2 | 16 | 8 | 0 | 1 |
| 2 | 17 | 9 | 0 | 1 |
| 1 | 18 | 10 | 1 (5 → 2 → 1) | 2 |
| -3 | 7 | -1 | 0 | 2 |
| 11 | 18 | 10 | 1 (-3 → 11) | 3 |
When the DFS reaches -3, the prefixes 15, 18, 21, 16 and 17 from the left subtree have all been removed, so the map holds only 0 and 10.
Answer: 3.
Path Sum III LeetCode Solution
A DFS that carries the prefix sum down and keeps a map of the prefixes on the current path. The C version brings its own small hash table.
Path Sum III Code
1var pathSum = function(root, targetSum) {2 const count = new Map([[0, 1]]);3 const dfs = (node, prefix) => {4 if (node === null) {5 return 0;6 }7 prefix += node.val;8 let found = count.get(prefix - targetSum) ?? 0;9 count.set(prefix, (count.get(prefix) ?? 0) + 1);10 found += dfs(node.left, prefix);11 found += dfs(node.right, prefix);12 count.set(prefix, count.get(prefix) - 1);13 return found;14 };15 return dfs(root, 0);16};
Path Sum III in Python, Java, C++, TypeScript and C
Path Sum III in Python
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
count = defaultdict(int)
count[0] = 1
def dfs(node, prefix):
if node is None:
return 0
prefix += node.val
found = count[prefix - targetSum]
count[prefix] += 1
found += dfs(node.left, prefix)
found += dfs(node.right, prefix)
count[prefix] -= 1
return found
return dfs(root, 0)Path Sum III in Java
class Solution {
private final Map<Long, Integer> count = new HashMap<>();
public int pathSum(TreeNode root, int targetSum) {
count.put(0L, 1);
return dfs(root, 0L, targetSum);
}
private int dfs(TreeNode node, long prefix, int target) {
if (node == null) {
return 0;
}
prefix += node.val;
int found = count.getOrDefault(prefix - target, 0);
count.merge(prefix, 1, Integer::sum);
found += dfs(node.left, prefix, target);
found += dfs(node.right, prefix, target);
count.merge(prefix, -1, Integer::sum);
return found;
}
}Path Sum III in C++
class Solution {
unordered_map<long long, int> count;
int dfs(TreeNode* node, long long prefix, int target) {
if (node == nullptr) {
return 0;
}
prefix += node->val;
auto it = count.find(prefix - target);
int found = it == count.end() ? 0 : it->second;
count[prefix]++;
found += dfs(node->left, prefix, target);
found += dfs(node->right, prefix, target);
count[prefix]--;
return found;
}
public:
int pathSum(TreeNode* root, int targetSum) {
count[0] = 1;
return dfs(root, 0, targetSum);
}
};Path Sum III in TypeScript
function pathSum(root: TreeNode | null, targetSum: number): number {
const count = new Map<number, number>([[0, 1]]);
const dfs = (node: TreeNode | null, prefix: number): number => {
if (node === null) {
return 0;
}
prefix += node.val;
let found = count.get(prefix - targetSum) ?? 0;
count.set(prefix, (count.get(prefix) ?? 0) + 1);
found += dfs(node.left, prefix);
found += dfs(node.right, prefix);
count.set(prefix, count.get(prefix)! - 1);
return found;
};
return dfs(root, 0);
}Path Sum III in C
#define SIZE 4096
typedef struct {
long long key;
int count;
int used;
} Slot;
static Slot table[SIZE];
/* Open addressing; at most 1,000 prefixes ever go in. */
static Slot* find(long long key) {
unsigned long long h = (unsigned long long)key * 11400714819323198485ull;
int i = (int)(h >> 52);
while (table[i].used && table[i].key != key) {
i = (i + 1) & (SIZE - 1);
}
return &table[i];
}
static int dfs(struct TreeNode* node, long long prefix, int target) {
if (node == NULL) {
return 0;
}
prefix += node->val;
Slot* need = find(prefix - target);
int found = need->used ? need->count : 0;
Slot* own = find(prefix);
own->used = 1;
own->key = prefix;
own->count++;
found += dfs(node->left, prefix, target);
found += dfs(node->right, prefix, target);
own->count--;
return found;
}
int pathSum(struct TreeNode* root, int targetSum) {
memset(table, 0, sizeof(table));
Slot* zero = find(0);
zero->used = 1;
zero->key = 0;
zero->count = 1;
return dfs(root, 0, targetSum);
}Edge Cases & Common Mistakes
- Forgetting
count[0] = 1: paths that start at the root are missed. - Recording the prefix before the lookup: with target 0 every node would match itself and count a path of length zero.
- Not backtracking: a prefix from a finished subtree lets a node in a sibling subtree count a path that is not downward.
- Negative values: a running sum can return to an earlier value, so several ancestors may share one prefix; that is why the map counts rather than stores a flag.
- Overflow: sums of up to 1,000 values of size 10⁹ need 64-bit integers.
Summary
DFS with a running prefix sum and a hash map of the prefixes on the current path, seeded with count[0] = 1. At each node add count[prefix − target], record the prefix, recurse, then remove it. O(n) time, O(n) space.
More practice: DSA interview questions with answers · patterns cheat sheet
