# 437. Path Sum III

## 1.問題

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LYKPJsg6tPgTWInD4bM%2F-LYKPOdsRAMKyH4tjmBy%2Fimage.png?alt=media\&token=fd1b1cf2-81a8-460c-bf58-220dad44507e)

## 2.想法&#x20;

* 計算路徑和等於某數值的個數
* DFS: 順序為L->R->V

## 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:  
  int result = 0;
  int pathSum(TreeNode* root, int sum) {
        if(root == NULL){
            return 0;
        }
      
        pathSum(root->left, sum);
        pathSum(root->right, sum);
        dfs(root, sum);
        return result;
    }
    
    void dfs(TreeNode* root, int sum) {
        if(root == NULL) {
            return;    
        }
        
        if(root->val == sum) {
            result++;
        }
        dfs(root->left, sum - root->val);
        dfs(root->right, sum - root->val);
    }
};
```
