112. Path Sum
Given the root of a binary tree and an integer targetSum, returns true if the tree has a path from root to leaf such that the addition of all values along the path equals targetSum.
A leaf is a node that has no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Description : Shows the path from the root to the leaf containing the goal sum.
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: false
Description: The tree has two root-to-leaf paths:
(1 --> 2 ) : the sum is 3.
(1 --> 3): Total is 4.
There is no path from root to leaf with sum = 5.
Example 3:
Input: root = [], targetSum = 0
Output: false
Description: There is no root because the tree is empty - the path to the sheet.
Limits:
The number of nodes in the tree is in the range [0, 5000].
-1000 <= Node.val <= 1000
-1000 <= TargetSum <= 1000
Solution
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum)
{
if (!root)
return false;
if (root->val==targetSum && !root->left && !root->right)
return true;
return hasPathSum(root->left, targetSum-root->val) || hasPathSum(root->right, targetSum-root->val);
}
};
Comments
Post a Comment