题目
解析
/**
* 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 {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return root.val == targetSum; // targetsum逐层往下减少,如果遇到叶子节点且两者相等,也就是targetsum-root.val == 0就返回true,不然就返回false
}
// 如果没遇到叶子节点就继续找叶子节点,targetSum - root.val就是在每一个分岔路口,都进行左右两边判断,所以可以遍历每条路径
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}