day18
思路和上一题类似。只不过path里面的元素需要手动 push pop
注意点:
1. vector 都要定义在外面,不然每次递归都会创建新的vector
2. 在最后叶子结点的时候,如果符合条件,就不用再插入叶子结点到path里面了。因为在调用之前就已经插入到path中了
3. 在主函数中,要先将root->val 的值插入path中,因为已经遍历了这个结点。
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> traversal(TreeNode* root, int count)
{
if(root->left == nullptr && root->right == nullptr && count == 0)
{
res.push_back(path); // 只需要插入 path 即可
return res;
}
if(root->left == nullptr && root->right == nullptr && count != 0)
return res;
// 要向左遍历
if(root->left)
{
// 在这里就已经把结点加入到 path 中了
path.push_back(root->left->val);
traversal(root->left, count - root->left->val);
path.pop_back();
}
if(root->right)
{
path.push_back(root->right->val);
traversal(root->right, count - root->right->val);
path.pop_back();
}
return res;
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> res;
if(root == nullptr)
return res;
path.push_back(root->val); // 别忘了要插入根结点!!
res = traversal(root,targetSum - root->val);
return res;
}
};