给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:本题与112题极其相似只需要在递归终止的时候增加两个数组来将符合条件的值装入数组中其他逻辑相同。
/**
* 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:
void travsal(TreeNode* root,int count,vector<int>&path,vector<vector<int>>&res)
{
if(!root->left&&!root->right&&count==0)
{
res.push_back(path);
return ;
}//递归终止条件的判断
if(!root->left&&!root->right) return;//递归终止条件
if(root->left){
count-=root->left->val;
path.push_back(root->left->val);
travsal(root->left,count,path,res);//递归
count+=root->left->val;//回溯
path.pop_back();//回溯
}
if(root->right){
count-=root->right->val;
path.push_back(root->right->val);
travsal(root->right,count,path,res);//递归
count+=root->right->val;//回溯
path.pop_back();//回溯
}
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<int>path;
vector<vector<int>>result;
path.clear();
result.clear();
if(root==NULL) return result;
path.push_back(root->val);
travsal(root,targetSum-root->val,path,result);
return result;
}
};