oneby7

Binary Trees Depth first: return a value up

361. Path Sum III

Medium

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

A downward path starts at any node and goes down, one child at a time, to any node below it, or stops at the node it started from. It does not have to start at the root or end at a leaf. It never goes up, so it cannot pass through a node from one child to the other. A single node is a path on its own. Two paths are different if they start or end at different nodes. An empty tree has no paths.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

56-30237-5

Input: root = [2, 5, 7, null, -3, 3, -5, 6, 0] targetSum = 2

Output: 4

Explanation: Four paths add up to 2: the root 2 on its own, 5 → −3, 5 → −3 → 0, and 7 → −5. The path 5 → −3 stops above the leaves, and adding the 0 below it makes a second path with the same sum.

Example 2

1-2-1-34-1

Input: root = [-1, -2, 4, 1, null, -3, -1], targetSum = -3

Output: 2

Explanation: −1 → −2 starts at the root and stops above the leaf 1. The other path is the single node −3.

Example 3

-11-11

Input: root = [1, -1, null, 1, null, -1], targetSum = 0

Output: 4

Explanation: The tree is one path, 1 → −1 → 1 → −1. Four stretches of it add up to 0: the first two nodes, the middle two, the last two, and all four.

Check your understanding

Work out the answer for this input before you write any code.

root = [0, 0, 0], targetSum = 0

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • -1012 ≤ targetSum ≤ 1012
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.