Problem · Tree
Path Sum
Learn this problemProblem statement
Given the root of a binary tree and an integer targetSum, return true if the tree contains a root-to-leaf path whose node values add up to targetSum. Otherwise, return false.
A leaf is a node with no left child and no right child. The path must begin at the root and end at a leaf.
An empty tree has no root-to-leaf path, so it returns false for every target.
Function
hasPathSum(root: TreeNode, targetSum: int) → booleanExamples
Example 1
root = [5,4,8,11,null,13,4,7,2,null,null,null,1]targetSum = 22return = trueThe root-to-leaf path 5 → 4 → 11 → 2 has sum 22.
Example 2
root = [1,2,3]targetSum = 5return = falseThe two root-to-leaf sums are 1 + 2 = 3 and 1 + 3 = 4, so neither equals 5.
Example 3
root = []targetSum = 0return = falseThe tree is empty, so it has no root-to-leaf path.
Constraints
- The tree contains at most
5000nodes. - Each node value is between
-1000and1000, inclusive. -10^9 <= targetSum <= 10^9