Skip to the code
cf.
+50 XP

#357 Downward Runs That Hit a Target

hard

An analytics view shows a tree of nested funnel steps, each with a change in conversions (which can be negative). An analyst asks: how many downward runs add up to exactly target? A run starts at any node and goes down through children to any node below it (or stops right away). It doesn't need to start at the root or end at a leaf.

Write countRuns(root, target) that returns the number of downward runs whose values sum to target. An empty tree returns 0.

Example 1

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

5 → 3, 5 → 2 → 1, and -3 → 11.

Example 2

Input: root = [2,-2,3,null,null,-3], target = 0
Output: 2

2 → -2 and 3 → -3. A run may start below the root.

Constraints

  • 0 <= number of nodes <= 1000
  • -10^5 <= value <= 10^5
  • -10^6 <= target <= 10^6

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).