437. Path Sum III

1.問題

2.想法

  • 計算路徑和等於某數值的個數

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

Last updated