一:题目
二:上码
/**
* 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 {
private int sum = 0;
private boolean ans = false;
public void preOrder(TreeNode root,int targetSum) {
if (root == null) return;
if (root.left == null && root.right == null) {
if (sum == targetSum) {
ans = true;
}
}
if (root.left != null) {//这里没有对root.left的判空 对于 root.left.val;
sum += root.left.val;
preOrder(root.left,targetSum);
sum -= root.left.val;
}
if (root.right != null) {
sum += root.right.val;
preOrder(root.right,targetSum);
sum -= root.right.val;
}
}
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null && targetSum == 0) return false;
if (root != null) sum = root.val;
preOrder(root,targetSum);
return ans;
}
}