Path sum
Standard · Write code · about 10 min
Given the root of a binary tree and an integer targetSum, return true when some path from the root down to a leaf has values that add up to targetSum. A leaf is a node with no children.
Example 1
Input:
[[5,4,8,11,null,13,4,7,2,null,null,null,1],22]
Output:
true
The path 5 → 4 → 11 → 2 adds up to 22.
Example 2
Input:
[[1,2,3],5]
Output:
false
The two paths add up to 3 and 4.
Constraints
- 0 ≤ number of nodes ≤ 1,000
- -1,000 ≤ Node.val ≤ 1,000
- The tree is given in level order; null marks a missing child
- -100,000 ≤ targetSum ≤ 100,000
Learn the idea first: Recursive problems on trees: height, size, mirror, paths, a visual lesson.
More Recursive problems on trees: height, size, mirror, paths problems
- Who reports first? Warm-up
- Complete the node counter Warm-up
- Max depth Standard
- Invert a tree Standard
- Same tree Standard
- Fix the height function Standard
- Diameter of a tree Challenge