[Leet Code]Path Sum
4760 ワード
簡単な問題ですが、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;
}
}
}