> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/tree/112.-path-sum.md).

# 112. Path Sum

![](/files/-Ml7L6dceiBeC6iymOlD)

![](/files/-Ml7L9S_ZAYHsbK2dk76)

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