Count Paths with Target Sum
Given the root of a binary tree and an integer target_sum, return how many paths have values that add up to target_sum.
A path doesn't have to start at the root or end at a leaf, but it must go downward, from parent to child.
Trees in the examples and tests are written in level order, with null for a missing child.
Example 1
Input: root = [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1], target_sum = 8 Output: 3 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1
The paths are 5 → 3, 5 → 2 → 1 and -3 → 11.
Example 2
Input: root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1], target_sum = 22 Output: 3
Constraints
- The tree has between
0and1000nodes. -1000 <= Node.val <= 1000-1000000 <= target_sum <= 1000000
Approach
Starting a search from every node and adding values on the way down works, but it takes O(n²) time on a tree that's a long chain. Prefix sums do it in one pass. Walk the tree with a depth-first search and keep the running sum from the root to the current node. Any downward path that ends at the current node is the difference between the current running sum and an earlier one on the same root-to-node path.
So keep a hash map that counts the running sums on the current path, seeded with {0: 1} for paths that start at the root. At each node, add the count for prefix - target_sum to the answer, record the node's own running sum and visit its children. When the search returns from the node, decrease that count again, so sums from one branch never leak into another.
Steps
- Create a map
seen = {0: 1}. - Search the tree, passing down the running sum. At each node, add its value to the sum.
- Add
seen[prefix - target_sum](or 0) to the count, then increaseseen[prefix]by 1. - Add the counts from both children, decrease
seen[prefix]by 1 and return the total.
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def path_sum(root: Optional[TreeNode], target_sum: int) -> int:
seen = {0: 1} # prefix sums on the current root-to-node path -> how many times each appears
def dfs(node: Optional[TreeNode], prefix: int) -> int:
if node is None:
return 0
prefix += node.val
count = seen.get(prefix - target_sum, 0) # paths ending here that start lower down
seen[prefix] = seen.get(prefix, 0) + 1
count += dfs(node.left, prefix) + dfs(node.right, prefix)
seen[prefix] -= 1 # leaving this node, so its prefix is no longer on the path
return count
return dfs(root, 0)Complexity
- Time:
O(n). Each node does constant work with the hash map. - Space:
O(h)for the map and the recursion, wherehis the height of the tree. That'sO(n)for a tree shaped like a chain.
Common mistakes
- Forgetting to remove the node's running sum on the way back up. Sums from the left subtree then count toward paths in the right subtree, which aren't connected.
- Leaving out the
{0: 1}entry, which misses paths that start at the root. - Recording the current sum before looking up
prefix - target_sum. Whentarget_sumis 0, that counts an empty path.