LeetCode No. 112. Path Sum
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null){
return false;
}
return sumOfPath(root, 0, targetSum);
}
public boolean sumOfPath(TreeNode cur, int sum, int target){
if(cur == null){
return false;
}
sum += cur.val;
if(cur.left == null && cur.right == null){
return sum==target;
}
return sumOfPath(cur.left, sum, target) || sumOfPath(cur.right,sum, target);
}
Top comments (0)