Skip to content
Decoder

Path Sum III

Medium

Problem

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.

Example 1

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

Example 2

Input
(5
Output
3, 5 -> 2 -> 1, -3 -> 11)

Example 3

Input
root = [0, 0, 0], targetSum = 0
Output
5

Constraints

  • 0 <= number of nodes <= 1000
  • -10^9 <= Node.val <= 10^9
  • -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.