---
# System prepended metadata

title: 'LeetCode #112 [Path Sum](https://leetcode.com/problems/path-sum/)'
tags: [Recursion, LeetCode, Easy, Tree]

---

###### tags: `LeetCode` `Tree` `Recursion` `Easy`
# LeetCode #112 [Path Sum](https://leetcode.com/problems/path-sum/)
### (Easy)

給你二元樹的根節點 root 和一個表示目標和的整數 targetSum ，判斷該樹中是否存在 根節點到葉子節點 的路徑，這條路徑上所有節點值相加等於目標和 targetSum 。

葉子節點 是指沒有子節點的節點。


---
當某個節點的值與targetSum相等且該節點為葉節點時回傳true。


---
```
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(!root)return false;
        if(!root->left&&!root->right&&root->val==targetSum)return true;
        else if(!root->left&&!root->right&&root->val!=targetSum)return false;
        return hasPathSum(root->left, targetSum-root->val)||hasPathSum(root->right, targetSum-root->val);
    }
};
```