给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例: 给定如下二叉树,以及目标和 sum = 22
class Solution {
private:
void dfs_find(TreeNode* cur,int sum,int targetSum,vector<int> &path,vector<vector<int>> &res)
{
path.push_back(cur->val);
if(cur->left==nullptr && cur->right==nullptr)
{
if(sum == targetSum){
res.push_back(path);
}
return;
}
if(cur->left){
dfs_find(cur->left,sum + cur->left->val,targetSum,path,res);
path.pop_back();
}
if(cur->right){
dfs_find(cur->right,sum + cur->right->val,targetSum,path,res);
path.pop_back();
}
}
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> res;
vector<int> path;
if(root==nullptr) return res;
dfs_find(root,root->val,targetSum,path,res);
return res;
}
};
标签:cur,res,sum,ii,vector,targetSum,113,path,总和
From: https://www.cnblogs.com/lihaoxiang/p/17296284.html