Path Sum
1 approach, code in every language
Problem description
You are given the root of a binary tree and an integer target. Determine whether the tree contains any root-to-leaf path whose node values add up exactly to the target. A leaf is a node with no children.
Return true if such a path exists and false otherwise. An empty tree contains no path and should return false.
Example 1
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], target = 22
Output: true
The path 5 -> 4 -> 11 -> 2 sums to 22, so a qualifying root-to-leaf path exists.
Example 2
Input: root = [1,2,3], target = 5
Output: false
The only root-to-leaf sums are 1+2=3 and 1+3=4, neither of which equals 5.
Constraints
The number of nodes is in the range [0, 5 * 10^3]-10^3 ≤ Node.val ≤ 10^3-10^3 ≤ target ≤ 10^3
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
A Branch Whose Loads Add Up is our own problem on the technique behind Path Sum: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free