path-sum-iii.sh — zsh
binary-treedepth-first-searchprefix-sumhash-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 for root is a LeetCode-style level-order array such as [10,5,-3,3,2,null,11,3,-2,null,1], using null for missing children)
  • Output: int

Examples

  1. root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 returns 3.
  2. root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 returns 3.
  3. root = [] , targetSum = 0 returns 0.

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