AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Path Sum III

The key idea

Any downward path equals the difference of two root-to-node running sums. Walk the tree once, keep the running sum from the root, and at each node count how many earlier prefix sums equal (running sum - targetSum). A hash map of prefix-sum counts turns the O(n^2) double walk into a single O(n) pass.

Problem

Given the root of a binary tree and an integer targetSum, return the number of downward paths whose node.val values add up to targetSum. A path does not need to start at the root or end at a leaf, but it must go downward, moving only from a parent node to one of its child nodes.

Constraints

Examples

Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 Output: 3
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: 3

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems