Binary Trees Depth first: return a value up
358. Path Sum
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
Input: root = [4, 9, -3, 2, null, 6, 8, null, null, -5]
targetSum = 9
trueExplanation: 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
Input: root = [-2, 5, null, -4, 1], targetSum = 3
falseExplanation: 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
falseExplanation: 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.
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.