我自己的写法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
boolean flag = false;
int pro = 0;
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null){
return flag;
}
PathSum(root,sum);
return flag;
}
public void PathSum(TreeNode root,int sum){
if(root == null)
return;
if(root.left == null && root.right == null){
pro += root.val;
if(pro == sum){
flag = true;
return;
}
pro -= root.val;
return;
}
pro += root.val;
PathSum(root.left,sum);
if(flag) return;
PathSum(root.right,sum);
if(flag) return;
pro -= root.val;
}
}
别人的写法,太优美了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null){
return false;
}
sum -= root.val;
if(root.left == null && root.right == null){
return sum == 0;
}
return hasPathSum(root.left,sum) || hasPathSum(root.right,sum);
}
}