Problem 482989 · medium · Level 04 Non-Linear Data Structures

Count Downward Paths With a Given Sum

binary tree · prefix sums · hash map · recursion

Given the root of a binary tree and an integer target, count the number of downward paths whose values add up to target. A downward path may start at any node and end at any node below it, but it must always move from a parent to a child. A path may consist of a single node.

Examples

        4
       / \
      2   -1
     /   /  \
   -1   6    3
       / \    \
     -2   5    -4

Input:  root = build_tree([4, 2, -1, -1, None, 6, 3, None, None, -2, 5, None, -4]), target = 5
Output: 3
Explanation: 4->2->-1, -1->6 and the single node 5 all sum to 5.

Input:  root = build_tree([1, 1, 1]), target = 1
Output: 3

Input:  root = build_tree([1, -1, 2]), target = 0
Output: 1
Explanation: only 1 -> -1 adds up to 0; a path always has at least one node.

Constraints

  • 0 <= number of nodes <= 1000
  • -1000 <= node.val <= 1000, -10**6 <= target <= 10**6

Goals

  • Extend the prefix-sum trick from arrays to root-to-node paths
  • Undo a bookkeeping change when a recursive call returns
Starting Python…