Skip to main content

Count Paths with Target Sum

MediumPremium

Given the root of a binary tree and an integer target_sum, return how many paths have values that add up to target_sum.

A path doesn't have to start at the root or end at a leaf, but it must go downward, from parent to child.

Trees in the examples and tests are written in level order, with null for a missing child.

Example 1

Input: root = [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1], target_sum = 8 Output: 3 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1

The paths are 5 → 3, 5 → 2 → 1 and -3 → 11.

Example 2

Input: root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1], target_sum = 22 Output: 3

Constraints

  • The tree has between 0 and 1000 nodes.
  • -1000 <= Node.val <= 1000
  • -1000000 <= target_sum <= 1000000