Binary Trees Depth first: return a value up
359. Path Sum II
You are given root, the root node of a binary tree, and an integer targetSum. Return every root-to-leaf
path whose values add up to exactly targetSum. Give each path as the list of its node values, from the
root down to the leaf.
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. Two
paths that end at different leaves are different paths, even when they hold the same values, so both are
listed. An empty tree has no paths, and its answer is [].
The paths can come back in any order. The examples sort them the way a dictionary sorts words, comparing the first values, then the second values, and so on.
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 = [2, 7, -3, 3, -1, 13, 5, null, null, 4, null, null, 6]
targetSum = 12
[[2,7,-1,4],[2,7,3]]Explanation: 2 → 7 → 3 and 2 → 7 → −1 → 4 both end at a leaf and add up to 12. The path 2 → −3 → 13 also adds up to 12, but 13 has a child, so it is not a leaf. Going on to 6 gives 18.
Example 2
Input: root = [], targetSum = 0
[]Explanation: The tree is empty, so it has no root-to-leaf paths, not even one with the sum 0.
Example 3
Input: root = [-5, 5, 5], targetSum = 0
[[-5,5],[-5,5]]Explanation: Both paths add up to 0. They hold the same values, but they end at different leaves, so the answer lists both.
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.
- The paths in the answer hold at most 106 values in all.
Clarifying questions
What you would ask an interviewer before writing any code.