oneby7

Binary Trees Depth first: return a value up

358. Path Sum

Easy

You are given root, the root node of a binary tree, and an integer targetSum. Return true if the tree has a root-to-leaf path whose values add up to exactly targetSum, and false otherwise.

A leaf is a node with no children. A root-to-leaf path starts at the root and goes down, one child at a time, until it reaches a leaf. A node with only one child is not a leaf, so a path cannot stop there. An empty tree has no paths at all.

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

294-56-38

Input: root = [4, 9, -3, 2, null, 6, 8, null, null, -5] targetSum = 9

Output: true

Explanation: The path 4 → −3 → 8 ends at the leaf 8 and sums to 9. The other two root-to-leaf paths, 4 → 9 → 2 and 4 → −3 → 6 → −5, sum to 15 and 2.

Example 2

-451-2

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

Output: false

Explanation: The path −2 → 5 sums to 3, but 5 has children, so it is not a leaf. The two root-to-leaf paths sum to −2 + 5 − 4 = −1 and −2 + 5 + 1 = 4.

Example 3

Input: root = [], targetSum = 0

Output: false

Explanation: The tree is empty, so it has no root-to-leaf paths, not even one with the sum 0.

Check your understanding

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

root = [1, 2, 3, null, null, null, 4], targetSum = 4

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.