题目链接:https://leetcode-cn.com/problems/path-sum-iii/
题目如下:
/**
* 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 pathSum(TreeNode* root, int targetSum) {
//双重递归
//先先序遍历(《根》左右)所有节点,再以每个节点为起点寻找满足条件的路径
dfs(root,targetSum);
return res;
}
void dfs(TreeNode* root,int targetSum){
//用于遍历每个节点
if(!root) return;
sum+=root->val;
get_path(root,targetSum);
sum-=root->val;
dfs(root->left,targetSum);
dfs(root->right,targetSum);
}
void get_path(TreeNode* root,int targetSum){
//用于计算从每个节点开始,满足条件的数量
if(!root) return ;
if(sum==targetSum){
res++;
}
if(root->left){
sum+=root->left->val;
get_path(root->left,targetSum);
sum-=root->left->val;
}
if(root->right){
sum+=root->right->val;
get_path(root->right,targetSum);
sum-=root->right->val;
}
}
private:
long long sum=0;
long long res=0;
};