terminal case 2: root.left == null, root.right == null, ไปฃ่กจๅฐ leaf ไบ, ๆไปฅๆญคๆ่ฆ check ็ตๆๆฏๅฆๆญฃ็ขบ (sum == targetSum or ๅฆๆๆฏ็จๆธ็, chack root.val == targetSum
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return helper(root, 0, sum);
}
private boolean helper(TreeNode root, int total, int givenSum) {
if (root == null) {
return false;
}
total += root.val;
if (root.left == null && root.right == null && total == givenSum) {
return true;
}
return helper(root.left, total, givenSum) || helper(root.right, total, givenSum);
}
}
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
return dfs(root, targetSum, 0);
}
private boolean dfs(TreeNode root, int targetSum, int sum) {
if (root == null) {
return false;
}
sum += root.val;
if (root.left == null && root.right == null && targetSum == sum) {
return true;
}
boolean left = dfs(root.left, targetSum, sum);
boolean right = dfs(root.right, targetSum, sum);
return left || right;
}
}
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return (root.val == sum);
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}