Three questions with the same name and a growing difficulty. They share one lesson because each one builds on the last:
root and targetSum, is there a root-to-leaf path whose values add up to targetSum? Return true or false.targetSum, as lists of values.targetSum, where a path may start and end anywhere, as long as it goes downward (parent to child).root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1], targetSum = 22
Path Sum I -> true
Path Sum II -> [[5, 4, 11, 2], [5, 8, 4, 5]]
root = [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1], targetSum = 8
Path Sum III -> 3 (5 -> 3, 5 -> 2 -> 1, -3 -> 11)The key idea for I and II: instead of adding values up and comparing at the end, carry the remaining amount down. Each node subtracts its value; a leaf that receives exactly 0 remaining finishes a matching path. (Values can be negative, so you can't stop early just because the sum got big.)
Free account
Sign up to read the rest of this lesson: 8 more sections, 3 drawings, 2 dry-run simulators and code in JavaScript, Python, Java and C++.
Still to come