MediumTreeDepth-First SearchBinary Tree

Path Sum III

LeetCode
1 approach, code in all languages

You are given the root of a binary tree and an integer targetSum. Count the number of paths whose node values add up to targetSum.

The path does not have to start at the root or end at a leaf, but it must travel strictly downward: it always moves from a parent node to one of its children. Two paths are considered different if they cover a different set of nodes.

Return the total count of such downward paths.

Example 1

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

Output: 3

Three downward paths sum to 8: 5 -> 3, 5 -> 2 -> 1, and -3 -> 11.

Example 2

Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22

Output: 3

There are three downward paths whose node values total 22.

Constraints

  • The number of nodes in the tree is in the range [0, 1000].
  • -10^9 <= Node.val <= 10^9
  • -1000 <= targetSum <= 1000
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now