Path Sum III
Medium
Topics
Given the root of a binary tree and an integer targetSum (passed as k), return the number of downward paths (parent to child, any start and end node) whose node values sum to k.
Example 1
null marks a missing child.Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], k = 8 Output: 3
Example 2
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], k = 22 Output: 3
Constraints
- 0 <= number of nodes <= 1000
- -10^9 <= Node.val <= 10^9
- -1000 <= k <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
Paths run downward from any node to any descendant. Along a single root-to-node path, a downward path is just a contiguous run — so the sum of a path ending at the current node equals cur - prefix for some ancestor prefix. This is "count the subarrays summing to k" applied along every root path.
Carry a count of the prefix sums seen on the current path. At each node, the number of qualifying paths ending there is the number of times cur - k has been seen. The word current is the whole trick: the count must be undone on the way back out, or prefixes from one subtree get treated as ancestors of another.
Approach
- Seed the prefix count with
{0: 1}, so paths starting at the root are counted. - Descend, adding the node's value to the running prefix
cur. - Add
count[cur - k]to the answer. - Increment
count[cur], recurse into both children, then decrement it again.
Dry Run
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
k = 8
root path prefix look for found running total
10 10 2 0 0
10 5 15 7 0 0
10 5 3 18 10 1 1 <- 5 -> 3
10 5 3 3 21 13 0 1
10 5 3 -2 16 8 0 1
10 5 2 17 9 0 1
10 5 2 1 18 10 1 2 <- 5 -> 2 -> 1
10 -3 7 -1 0 2
10 -3 11 18 10 1 3 <- -3 -> 11
answer 3Complexity
- Time — O(n): one visit per node with constant expected map work.
- Space — O(n). Worth being careful here rather than writing O(h). The recursion is O(h) deep and only h prefix counts are ever live, but a default-valued map is never pruned and the lookup
count[cur - k]itself inserts the probed key. On a 1,000-node path the map peaks at 1,999 keys and still holds 1,999 at the end, 1,998 of them zero. Deleting entries as they fall to zero is what makes O(h) true.
Common Pitfalls
- Omitting the decrement on the way out. On a root of 1 with children 1 and 2 and
k = 1, that returns 3 instead of 2 — a prefix recorded in the left subtree is counted as an ancestor of the right one. - Forgetting
count[0] = 1, which drops every path that starts at the root. - Not offering the O(n²) baseline first. Running a separate downward count from every node is the honest naive answer, and at
n <= 1000it even passes; the prefix-count version is the improvement, and it reads better if the baseline is on the board. - Overflow. A thousand nodes at magnitudes up to 10⁹ put prefix sums near 10¹², so the running sum and the map keys must be 64-bit.
- Assuming values are positive and reaching for a sliding window. Negative values are allowed, which is exactly why prefix counting is needed rather than a two-pointer window that relies on monotonicity.
- Counting upward paths, or paths that bend through a parent. Only downward, parent-to-child paths qualify.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def pathSum(self, root, k):
from collections import defaultdict
cnt = defaultdict(int); cnt[0] = 1
self.total = 0
def dfs(node, cur):
if not node: return
cur += node.val
self.total += cnt[cur - k]
cnt[cur] += 1
dfs(node.left, cur); dfs(node.right, cur)
cnt[cur] -= 1
dfs(root, 0)
return self.totalimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int pathSum(TreeNode root, int k) {
map.clear();
map.put(0L, 1);
total = 0;
K = k;
dfs(root, 0L);
return total;
}
Map<Long,Integer> map = new HashMap<>();
int total;
int K;
private void dfs(TreeNode node, long cur) {
if (node == null) return;
cur += node.val;
total += map.getOrDefault(cur - K, 0);
map.put(cur, map.getOrDefault(cur, 0) + 1);
dfs(node.left, cur);
dfs(node.right, cur);
map.put(cur, map.get(cur) - 1);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int pathSum(TreeNode* root, int k) {
unordered_map<long long,int> cnt;
cnt[0] = 1;
int total = 0;
function<void(TreeNode*,long long)> dfs = [&](TreeNode* node, long long cur) {
if (!node) return;
cur += node->val;
total += cnt.count(cur - k) ? cnt[cur - k] : 0;
cnt[cur]++;
dfs(node->left, cur);
dfs(node->right, cur);
cnt[cur]--;
};
dfs(root, 0);
return total;
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/ var pathSum = function(root, k) {
const cnt = new Map();
cnt.set(0, 1);
let total = 0;
const dfs = (node, cur) => {
if (!node) return;
cur += node.val;
total += (cnt.get(cur - k) || 0);
cnt.set(cur, (cnt.get(cur) || 0) + 1);
dfs(node.left, cur);
dfs(node.right, cur);
cnt.set(cur, cnt.get(cur) - 1);
};
dfs(root, 0);
return total;
};