mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
1.3 KiB
1.3 KiB
113. Path Sum II
思路
给定一棵二叉树,求所有根到叶子路径中和为sum的路径。
考虑用DFS,遍历的时候用一维数组path记录当前经过的路径,每遍历一个节点就将其加入path,从这个结点返回时,需要把该节点从path中移除。如果当前节点是叶子节点而且
满足和为sum,即可将path加入到结果二维数组res中。
注:实现的时候我们可以将path和res设置成全局的,免得传参。
相当于遍历一遍二叉树,所以时空复杂度均为O(n)
C++
class Solution {
private:
vector<int>path;
vector<vector<int>>res;
void helper(TreeNode *root, int sum){
path.push_back(root -> val);
sum -= root -> val;
if((!root->left) && (!root -> right) && 0 == sum) res.push_back(path);
else{
if(root -> left) helper(root -> left, sum);
if(root -> right) helper(root -> right, sum);
}
// 返回父节点之前要删除路径上的当前节点
path.pop_back();
}
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
path.clear(); res.clear();
if(root) helper(root, sum);
return res;
}
};