视频:https://www.acwing.com/video/171/ 很好的展示了代码怎么写。
结合递归细品
class Solution {
public:
//int sum ;
vector<vector<int>> res; //答案数据,定义成类里面的全局变量
vector<int> path; //当前路径
vector<vector<int>> findPath(TreeNode* root, int sum) {
//sum = sum;
dfs(root, sum);//做减法,减到正好等于0时,就代表发现路径
return res;
}
void dfs(TreeNode *root, int sum) {
if(root == NULL) return;//当前节点为空,代表不是叶节点,直接return
path.push_back(root->val);
sum = sum - root->val;
//if(!root->left && !root->right && !sum):如果当前节点为叶节点,且是我们要找的路径(sum==0)
if(!root->left && !root->right && !sum) res.push_back(path); //使用递归时,一定要有明确的终止条件!
if(root->left) dfs(root->left, sum);
if(root->right) dfs(root->right, sum);
path.pop_back();//我们不光递归一个分支,还要去遍历其他分支,遍历完当前子树要把path清空
//根节点的左叶子节点满足条件了,还要看看右叶子节点满不满足条件
}
};
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> findPath(TreeNode* root, int sum) {
if(root == NULL) return res;
dfs(root,sum);
return res;
}
void dfs(TreeNode* root, int sum)
{
if(root == NULL) return;
sum = sum - root->val;
path.push_back(root->val);
if(root->left == NULL && root->right == NULL && sum == 0) res.push_back(path);
else
{
if(root->left) dfs(root->left,sum);
if(root->right) dfs(root->right,sum);
}
path.pop_back();
}
};