# 112. Path Sum

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-Ml7Il4qohyqwt1iR3nv%2F-Ml7L6dceiBeC6iymOlD%2Fimage.png?alt=media\&token=11ad60f5-9f91-4d68-bb4f-083819c575a1)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-Ml7Il4qohyqwt1iR3nv%2F-Ml7L9S_ZAYHsbK2dk76%2Fimage.png?alt=media\&token=b2b726d3-4ff1-43df-9b7b-b8c560618ae3)

[https://leetcode.com/problems/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

```java
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

```java
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

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