AlgoInsight

DSA problem

Path Sum III

MediumTree Traversal - Pre OrderPattern: Tree Traversal - Pre Ordertop75FreeAmazonGoogleMicrosoftAppleMetaBloomberg

Given the root of a binary tree and an integer targetSum, return the number of downward paths in the tree whose node values sum to targetSum. A downward path is any sequence of consecutive parent-to-child nodes — it does not have to start at the root or end at a leaf, but it must travel only downward.

The brute-force solution starts a fresh path-sum search at every node and tries to find continuations whose sum equals the target. That costs O(n²) in a balanced tree and O(n²) on average for a skewed tree, which is sometimes acceptable but rarely interesting.

The optimal approach borrows the classic prefix-sum hashmap trick from the 1-D "subarray sum equals K" problem. Treat the path from the root to the current node as a 1-D array of values, and maintain currSum = sum from the root to the current node. A downward path ending at the current node has sum targetSum iff there is some ancestor along that path whose root-to-ancestor sum is currSum - targetSum. So we keep a hash map from running prefix sum → frequency along the current root-to-node path; at every node we add freq[currSum - targetSum] to the answer, then bump freq[currSum], recurse, and decrement freq[currSum] on the way out so siblings do not see this contribution.

Use a 64-bit integer for currSum: with values as large as 10^9 and trees of up to 1000 nodes, partial sums can overflow a 32-bit int. The complexity is O(n) time and O(h) space — a one-pass preorder DFS, exactly the canonical pattern.

Examples

Example 1
Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
Explanation: Three downward paths sum to 8: 5 → 3, 5 → 2 → 1, and -3 → 11. Note that none of them needs to start at the root.
Example 2
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: 3
Explanation: Three paths sum to 22, including 5 → 4 → 11 → 2 and 5 → 8 → 4 → 5 and the single-node path of 22 if it existed; in this tree the three valid paths arise from different sub-paths as captured by the prefix-sum logic.
Example 3
Input: root = [1,-2,-3], targetSum = -1
Output: 2
Explanation: Paths -2 and -3 → 2 (if it existed) — actually the matching paths in this small tree are {-2} (subpath sum -2? no), and {1, -2} (sum -1). The single qualifying path is 1 → -2, plus the lone -3 path? — the count is exactly the number of downward sub-paths summing to -1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchprefix-sumhash-table

Browse all DSA problems