AcWing 437.. 路径总和 III
原题链接
中等
作者:
owonder
,
2020-09-07 13:53:11
,
所有人可见
,
阅读 608
C++ 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int pathcnt;
int pathSum(TreeNode* root, int sum) {
if(!root){
return 0;
}
dfs( root, sum);
pathSum(root->left,sum);
pathSum(root->right,sum);
return pathcnt;
}
void dfs(TreeNode* root, int sum){
if(!root){
return ;
}
if(sum==root->val){
pathcnt++;
}
dfs( root->left, sum-root->val);
dfs( root->right, sum-root->val);
}
};