题目比较简单,但是递归的方法有点启发,以往写这种递归,都会先设置一个sum标记之类的东西, 然后累加,再判断是不是答案的值,但是这题题解里的做法是传参一个sum,每次减去一个值,这样少一个变量而且递归写起来也比较方便,附上自己的代码和题解代码
class Solution {
public:
vector<vector<int > > ans;
vector<int > res;
int sum;
vector<vector<int>> findPath(TreeNode* root, int sum) {
this->sum = sum;
find_(root,0);
return ans;
}
void find_(TreeNode* root, int count) {
if(!root) return ;
res.push_back(root->val);
if(count+root->val == sum && !root->left && !root->right) {
ans.push_back(res);
}
find_(root->left, count+root->val);
find_(root->right, count+root->val);
res.pop_back();
}
};
题解做法:
class Solution {
public:
vector<vector<int > > ans;
vector<int > path;
vector<vector<int>> findPath(TreeNode* root, int sum) {
dfs(root, sum);
return ans;
}
void dfs(TreeNode* root, int sum) {
if(!root) return;
path.push_back(root->val);
sum-=root->val;
if(!root->left && !root->right && !sum) ans.push_back(path);
dfs(root->left, sum);
dfs(root->right, sum);
path.pop_back();
}
};