Skip to content

Path Sum III

MediumTrees
Decode it first. Clues, constraints, pattern and plan before any code.

Given the root of a binary tree and an integer targetSum, return the number of paths whose values add up to targetSum.

A path here can start and end at any node, but it must only go downward (from a parent to one of its children). A single node is a path too.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

root = [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1], targetSum = 8  →  3
    (5 -> 3,  5 -> 2 -> 1,  -3 -> 11)
root = [0, 0, 0],                                    targetSum = 0  →  5

Constraints

  • 0 <= number of nodes <= 1000
  • -10^9 <= Node.val <= 10^9
  • -1000 <= targetSum <= 1000