Path Sum III

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

30:00

Path Sum III
medium
Free written solution
Topics
Companies

Given the root of a binary tree and an integer targetSum, return the number of paths whose node values add up to targetSum. A path does not have to start at the root or end at a leaf, but it must go 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
Constraints:
  • The number of nodes in the tree is in the range [0,1000][0, 1000].

  • −109≤Node.val≤109-10^9 \leq \text{Node.val} \leq 10^9

  • −1000≤targetSum≤1000-1000 \leq \text{targetSum} \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[10,5,-3,3,2,null,11,3,-2,null,1],"targetSum":8}

Seed the map with {0: 1}: the empty prefix lets a path that starts at the root count too. Target is 8.

105-332113-21

prefix sums on the current path (root first)

start
0

count map

0: 1

total = 0

current node
current root path
path that sums to target
prefix counts in the map
Variables
VariableValue
targetSum8
nodenull
curr0
total0
DepthFunction Call
Stack empty
0/28