Binary Trees Depth first: return a value up
361. Path Sum III
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
Input: root = [2, 5, 7, null, -3, 3, -5, 6, 0]
targetSum = 2
4Explanation: 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
Input: root = [-1, -2, 4, 1, null, -3, -1], targetSum = -3
2Explanation: −1 → −2 starts at the root and stops above the leaf 1. The other path is the single node −3.
Example 3
Input: root = [1, -1, null, 1, null, -1], targetSum = 0
4Explanation: 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.
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.