Full answer
Problem
Given the root of a binary tree and an integer target, return the number of paths whose node values sum to target. A path must go downward (parent to child) but may start and end at any node.
Example: for the tree 10 -> (5 -> (3 -> 3, -2), (2 -> -, 1)), (-3 -> -, 11) and target 8 the answer is 3: 5 + 3, 5 + 2 + 1 and -3 + 11.
Constraints: up to 1,000 nodes; values from -10^9 to 10^9 (negatives allowed, so pruning by sign is not possible).
Warm-up: "is there a root-to-leaf path with sum target" is a plain DFS that subtracts each value and checks at leaves.
Brute force
From every node, start a DFS downward and count paths reaching the target. Each start costs O(subtree size), giving O(n * h): O(n log n) balanced, O(n^2) on a chain.
Optimal approach
Prefix sums on the root-to-node path:
seen = {0: 1}(the empty prefix, so paths starting at the root count).- At a node,
running += node.val. Paths ending here:seen[running - target]. - Increment
seen[running], recurse into both children, then decrement it before returning.
Why it works
The sum of the downward path from ancestor a (exclusive) to the current node equals running - prefix(a). That equals target exactly when prefix(a) = running - target, so the count of such ancestors is a hash lookup. Removing the current prefix on the way back keeps the map limited to the current root-to-node path, so prefixes from other branches never pair with this node.
Complexity
O(n) time with O(1) average hash operations. O(h) space for recursion and the map.
Code
import random
from collections import defaultdict
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def has_path_sum(root, target):
"""Root-to-leaf path summing to target (the warm-up)."""
if root is None:
return False
if root.left is None and root.right is None:
return root.val == target
rest = target - root.val
return has_path_sum(root.left, rest) or has_path_sum(root.right, rest)
def count_paths(root, target):
"""Downward paths (any start, any end) summing to target. Prefix sums: O(n)."""
seen = defaultdict(int)
seen[0] = 1 # empty prefix, so paths starting at the root count
def walk(node, running):
if node is None:
return 0
running += node.val
found = seen[running - target] # earlier prefixes that leave exactly target
seen[running] += 1
found += walk(node.left, running) + walk(node.right, running)
seen[running] -= 1 # backtrack: leave this root-to-node path
return found
return walk(root, 0)
def brute(root, target):
"""O(n * h): start a downward walk from every node."""
def from_node(n, rem):
if n is None:
return 0
rem -= n.val
return (rem == 0) + from_node(n.left, rem) + from_node(n.right, rem)
def every(n):
return 0 if n is None else from_node(n, target) + every(n.left) + every(n.right)
return every(root)
def random_tree(rng, depth):
if depth == 0 or rng.random() < 0.25:
return None
return TreeNode(rng.randint(-3, 3), random_tree(rng, depth - 1), random_tree(rng, depth - 1))
if __name__ == "__main__":
t = TreeNode(10, TreeNode(5, TreeNode(3, TreeNode(3), TreeNode(-2)), TreeNode(2, None, TreeNode(1))),
TreeNode(-3, None, TreeNode(11)))
assert count_paths(t, 8) == 3 # 5+3, 5+2+1, -3+11
assert has_path_sum(t, 18) and not has_path_sum(t, 100) # 10+5+3 is not a leaf path; 10+5+2+1 = 18
assert count_paths(None, 0) == 0
rng = random.Random(59)
for _ in range(2000):
r = random_tree(rng, 5)
k = rng.randint(-4, 4)
assert count_paths(r, k) == brute(r, k)
print("all tests passed")Save as b59_path_sum.py and run python3 b59_path_sum.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty tree (0). Target 0 with zero-valued nodes (single nodes count as paths). Negative values. Several equal prefix sums on one path (the counter, not a set, matters).
Pattern
This is the "subarray sum equals k" prefix-sum trick moved onto a tree, with backtracking to keep the state path-local. The same combination solves "longest path with a given XOR" and counting paths under modular constraints.
import random
from collections import defaultdict
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def has_path_sum(root, target):
"""Root-to-leaf path summing to target (the warm-up)."""
if root is None:
return False
if root.left is None and root.right is None:
return root.val == target
rest = target - root.val
return has_path_sum(root.left, rest) or has_path_sum(root.right, rest)
def count_paths(root, target):
"""Downward paths (any start, any end) summing to target. Prefix sums: O(n)."""
seen = defaultdict(int)
seen[0] = 1 # empty prefix, so paths starting at the root count
def walk(node, running):
if node is None:
return 0
running += node.val
found = seen[running - target] # earlier prefixes that leave exactly target
seen[running] += 1
found += walk(node.left, running) + walk(node.right, running)
seen[running] -= 1 # backtrack: leave this root-to-node path
return found
return walk(root, 0)
def brute(root, target):
"""O(n * h): start a downward walk from every node."""
def from_node(n, rem):
if n is None:
return 0
rem -= n.val
return (rem == 0) + from_node(n.left, rem) + from_node(n.right, rem)
def every(n):
return 0 if n is None else from_node(n, target) + every(n.left) + every(n.right)
return every(root)
def random_tree(rng, depth):
if depth == 0 or rng.random() < 0.25:
return None
return TreeNode(rng.randint(-3, 3), random_tree(rng, depth - 1), random_tree(rng, depth - 1))
if __name__ == "__main__":
t = TreeNode(10, TreeNode(5, TreeNode(3, TreeNode(3), TreeNode(-2)), TreeNode(2, None, TreeNode(1))),
TreeNode(-3, None, TreeNode(11)))
assert count_paths(t, 8) == 3 # 5+3, 5+2+1, -3+11
assert has_path_sum(t, 18) and not has_path_sum(t, 100) # 10+5+3 is not a leaf path; 10+5+2+1 = 18
assert count_paths(None, 0) == 0
rng = random.Random(59)
for _ in range(2000):
r = random_tree(rng, 5)
k = rng.randint(-4, 4)
assert count_paths(r, k) == brute(r, k)
print("all tests passed")Root-to-leaf warm-up, prefix-sum counter with backtracking, and an O(n * h) brute force cross-check on random trees with negatives.
Complexity
Time: O(n) average. Space: O(h). Hash-map operations are average O(1); the brute force is O(n * h).
By level
Fresher: Solves the root-to-leaf warm-up and the O(n * h) count from every node, explaining the cost. Follows the prefix-sum idea when shown the array version.
Mid: Writes the prefix-sum DFS with the seed and backtracking, and explains why order of lookup and insert matters. States O(n) average time.
Senior: Generalizes path-local state with backtracking to other tree aggregates and explains when a global map would give wrong answers. Discusses iterative implementations and integer overflow in languages with fixed-width types.
Key points
- Path sum = running - prefix of an ancestor
- Seed the map with {0: 1}
- Look up before inserting the current prefix
- Decrement when backtracking
- Negatives rule out early pruning
Common mistakes
- Forgetting the {0: 1} seed so paths from the root are missed
- Inserting the current prefix before the lookup, which counts empty paths when target is 0
- Not removing the prefix on return, so other branches leak in
- Using a set instead of counts
Follow-ups
- How would you return the paths themselves?
- What if paths can go up and then down (any two nodes)?
- How does the array version (subarray sum equals k) relate?
Tips
- Point out the link to the array problem
- Explain the backtracking step clearly
- Test with target 0
Evaluation rubric
- Correct prefix-sum logic
- Correct backtracking
- Handles negatives and target 0
- Correct complexity