使用两次dfs即可得到结果:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param sum int整型
* @return int整型
*/
int ans = 0;
void dfs(TreeNode *root, int sum){
if(root){
if(sum - root->val == 0) ans++;
dfs(root->left, sum - root->val);
dfs(root->right, sum - root->val);
}
}
int FindPath(TreeNode* root, int sum) {
if(!root) return ans;
dfs(root, sum); //先看以root为根结点的子树有几条路径
FindPath(root->left, sum); //再分别看root两边的子树有几条路径
FindPath(root->right, sum);
return ans;
}
};