root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回 3。和等于 8 的路径有:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
/**
* 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 {
private:
int res=0;
void getsum(TreeNode* root, int sum)
{
if(!root) return ;
sum-=root->val;
if(sum==0) res++;
getsum(root->left,sum);
getsum(root->right,sum);
}
public:
int pathSum(TreeNode* root, int sum) {
if(!root) return 0;
getsum(root,sum);
pathSum(root->left,sum);
pathSum(root->right,sum);
return res;
}
};
执行用时 : 28 ms, 在Path Sum III的C++提交中击败了97.19% 的用户
内存消耗 : 14.8 MB, 在Path Sum III的C++提交中击败了77.24% 的用户