思路:
dfs
代码:
/**
* 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:
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(!root) return {};
dfs(root,targetSum);
return res;
}
void dfs(TreeNode* root,int targetSum){
targetSum-=root->val;
path.push_back(root->val);
//找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
if(!root->left && !root->right && !targetSum){
res.push_back(path);
}
else{
if(root->left) dfs(root->left,targetSum);
if(root->right) dfs(root->right,targetSum);
}
path.pop_back();
}
};
评论区