Skip to content
Decoder

Path Sum

Easy

Problem

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.

Example 1

Input
root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], targetSum = 22
Output
True
Why
5 + 4 + 11 + 2

Example 2

Input
root = [1, 2, 3], targetSum = 5
Output
False

Example 3

Input
root = [1, 2], targetSum = 1
Output
False
Why
1 alone is not a leaf

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.