题目链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/
题目如下:
/**
* 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>> pathSum(TreeNode* root, int target) {
if(!root) return res;
sum+=root->val;
path.push_back(root->val);
dfs(root,target);
return res;
}
void dfs(TreeNode* root,int target){
if(!root->left&&!root->right){//此时走到叶子节点就需要判断是否要放入res中
if(sum==target) res.push_back(path);
return ;
}
if(root->left){
sum+=root->left->val;
path.push_back(root->left->val);
dfs(root->left,target);
path.pop_back();
sum-=root->left->val;
}
if(root->right){
sum+=root->right->val;
path.push_back(root->right->val);
dfs(root->right,target);
path.pop_back();
sum-=root->right->val;
}
}
private:
vector<vector<int>> res;
vector<int> path;
int sum=0;
};