Skip to content

Path Sum

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

Given the root of a binary tree and an integer targetSum, return True if there is a path from the root down to a leaf whose values add up to targetSum. A leaf is a node with no children.

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 = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], targetSum = 22  →  True   (5 + 4 + 11 + 2)
root = [1, 2, 3],                                              targetSum = 5   →  False
root = [1, 2],                                                 targetSum = 1   →  False  (1 alone is not a leaf)

Constraints

  • 0 <= number of nodes <= 5000
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000