112. Path Sum

https://leetcode.com/problems/path-sum/

terminal case 1: root == null, ๆœฌ่บซๅฐฑ null, ไธ€ๅฎšไธๅฐ

terminal case 2: root.left == null, root.right == null, ไปฃ่กจๅˆฐ leaf ไบ†, ๆ‰€ไปฅๆญคๆ™‚่ฆ check ็ตๆžœๆ˜ฏๅฆๆญฃ็ขบ (sum == targetSum or ๅฆ‚ๆžœๆ˜ฏ็”จๆธ›็š„, chack root.val == targetSum

ๅ…ถไป–ๅทฆๅณ้ๆญท

my version

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);
        
    }
}

or

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;
    }
}

better version

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);
    }
}

Last updated