InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Path Sum III

medium Original ↗ 00:00

Problem

Given the root of a binary tree and an integer targetSum, count how many downward paths in the tree have values summing to targetSum. A path may start at any node and end at any node below it, but it must go strictly downward (each step parent → child) and contain at least one node. Values may be negative, and the answer counts paths, not nodes.

Examples

  • Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 → Output: 3 The qualifying paths are 5 → 3, 5 → 2 → 1, and -3 → 11.
  • Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 → Output: 3 Paths: 5 → 4 → 11 → 2, 4 → 11 → 7, and 5 → 8 → 4 → 5.
  • Input: root = [1,-1,null,1], targetSum = 0 → Output: 2 In this left-leaning chain 1 → -1 → 1, the paths 1 → -1 and -1 → 1 each sum to 0; the full chain sums to 1 and single nodes don’t qualify.

Constraints

  • Up to 1000 nodes; -10^9 <= Node.val <= 10^9; -1000 <= targetSum <= 1000.
  • Negative values mean a running sum can revisit earlier totals — no pruning by “sum already too big”.
  • O(n²) passes at this size, but the intended solution is O(n).

Think about it first

Hint 1 Every downward path is described by two nodes: where it starts and where it ends. What if you fix the starting node and search downward from it?
Hint 2 In arrays, "count subarrays summing to k" is solved with prefix sums and a hash map: a subarray sums to k exactly when two prefixes differ by k. A root-to-node path is a prefix here.
Hint 3 DFS while carrying the running root-to-current sum and a hash map counting how often each prefix sum occurred on the current root path. At each node, add `count[current - targetSum]` to the answer — and decrement the node's own entry when backtracking so counts never leak across branches.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug