[Leet Code]Path Sum

时间:2023-03-09 02:47:29
[Leet Code]Path Sum

很简单一道题,搞错了N次,记录一下。

public class Solution {
private int currSum = 0; public boolean hasPathSum(TreeNode root, int sum) {
if (null == root)
return false; currSum = 0;
return hasPathSumCore(root, sum);
} public boolean hasPathSumCore(TreeNode root, int sum) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == root)
return true; currSum += root.val; boolean leftHas = false;
boolean rightHas = false; if (null == root.left && null == root.right) {
if (currSum == sum) {
currSum -= root.val;
return true;
}
else {
currSum -= root.val;
return false;
}
}
else if (null == root.left && null != root.right) {
rightHas = hasPathSumCore(root.right, sum);
currSum -= root.val;
return rightHas;
}
else if (null == root.right && null != root.left) {
leftHas = hasPathSumCore(root.left, sum);
currSum -= root.val;
return leftHas;
}
else {
leftHas = hasPathSumCore(root.left, sum);
rightHas = hasPathSumCore(root.right, sum);
currSum -= root.val;
return leftHas || rightHas;
}
}
}