Path Sum III
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.
The path does not need to start at the root or end at a leaf.
However, the path must always move downward, from parent nodes to child nodes.
Example 1
Input
root = [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1] targetSum = 8
Output
3
Explanation
The three paths whose sum is 8 are:
5 → 3
5 → 2 → 1
-3 → 11
Therefore, the answer is:
3
Example 2
Input
root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1] targetSum = 22
Output
3
Explanation
There are three downward paths whose values add up to 22.
Therefore, the answer is 3.
Constraints
Hints:
Hint 1
For every node, consider the paths that end at that node.
Hint 2
Maintain the prefix sum from the root to the current node.
If the current prefix sum is currentSum, we need an earlier prefix sum equal to:
currentSum - targetSum
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 26, 2026
Last updated
Aug 26, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output