原网址:https://leetcode.com/problems/path-sum-iii/discuss/91877/C%2B%2B-5-Line-Body-Code-DFS-Solution
解题思路:
(1)总的数目是以当前为根的数目加上以左孩子和右孩子分别为根的数目
(2)作者的双递归用的确实很惊艳
/**
* 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 pathSum(TreeNode* root, int sum) {
if(!root) return 0;
return sumUp(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
private:
int sumUp(TreeNode* root, int pre, int& sum){
if(!root) return 0;
int current = pre + root->val;
return (current == sum) + sumUp(root->left, current, sum) + sumUp(root->right, current, sum);
}
};