Path Sum III
medium
binary-tree
depth-first-search
prefix-sum
hash-map
Given the root of a binary tree and an integer targetSum, return the number of paths whose values add up to targetSum.
The path does not need to start at the root or end at a leaf, but it must move downward only (from parent to child along existing links).
Input / output
- Input:
root: TreeNode,targetSum: int(the JSON test fixture forrootis a LeetCode-style level-order array such as[10,5,-3,3,2,null,11,3,-2,null,1], usingnullfor missing children) - Output:
int
Examples
root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8returns3.root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22returns3.root = [] , targetSum = 0returns0.
Constraints
0 <= number of nodes <= 1000-10^9 <= Node.val <= 10^9-1000 <= targetSum <= 1000
Follow-up A brute-force DFS from every node works, but can you count all valid paths in a single traversal by combining a running prefix sum with a hash map of previously seen prefix sums?
Examples
Example 1
Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
Example 2
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: 3