# 112. Path Sum

## 1.問題

* 給予一個binary tree, 檢查是否有路徑總和等於sum

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJ91PFycCq0rOszH6wv%2F-LJ934JR2d8uBAFhcUL4%2F2018080503.jpg?alt=media\&token=a9ddc286-4af9-474b-8bdb-a64cdd784123)

## 2.想法

* 提問確認題意: &#x20;
  * binary tree的類型
* function header, parameter
* test input
* 觀察
  * DFS直到node == NULL時,只要sum ==0時return true
* 說明想法
  * 要確認的是"root to leaf的總和"是否等於某值
  * 因此base case有:
    * 當sum為0時回傳true, 當sum < 0時回傳false
    * 當左, 右child都不存在時, 回傳(sum == root->val)
  * 如果通過base case的檢查, 則L->V繼續迭代
    * left, right存在時才繼續迭代
  * 如果以上皆非則回傳false
* 測試計算複雜度

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) { 
        if (!root) {
            return false;
        }
        return checkSum(root, sum);
    }
private:
    bool checkSum(TreeNode* root, int sum) {
        if (!root) {
            if (sum == 0) {
                return true;
            } else {
                return false;
            }
        }
        //cout<<sum<<endl;
        if (root->left == NULL && root->right == NULL) {            
            return sum == root->val;        
        }
        
        if (root->left && checkSum(root->left, sum - root->val)) {
            return true;
        }
        if (root->right && checkSum(root->right, sum - root->val)) {
            return true;
        }
        return false;
        
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJ91PFycCq0rOszH6wv%2F-LJ95_sPc8xQ_KymgLSs%2F2018080504.jpg?alt=media\&token=689c2a43-7204-434b-8529-428ddb5765ff)
