# 每日算法-路径总和

### 题目

输入：root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22



输入：root = [1,2,3], targetSum = 5



输入：root = [1,2], targetSum = 0



• 树中节点的数目在范围 [0, 5000] 内
• -1000 <= Node.val <= 1000
• -1000 <= targetSum <= 1000

### 解法

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode() {}
*     TreeNode(int val) { this.val = val; }
*     TreeNode(int val, TreeNode left, TreeNode right) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*     }
* }
*/
class Solution {
// 递归
// 假定从根节点到当前节点的值之和为 val，我们可以将这个大问题转化为一个小问题：
// 是否存在从当前节点的子节点到叶子的路径，满足其路径和为 sum - val。
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null){
return false;
}
TreeNode left = root.left;
TreeNode right = root.right;
int val = root.val;
if(left == null || right == null){
if(left == null && right == null){
return targetSum == val;
}else if (left != null){
return hasPathSum(left,targetSum-val);
} else {
return hasPathSum(right,targetSum-val);
}
}

return hasPathSum(left,targetSum-val) || hasPathSum(right,targetSum - val);
}
}


### 总结

11-12 880

04-21 2万+
10-07 6767
05-03 339
10-24 345
08-15 474
08-12 61
11-20 2250
©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客