mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
update 113
This commit is contained in:
parent
3e7d3578b5
commit
b7b1fba255
@ -5,6 +5,8 @@
|
||||
满足和为sum,即可将path加入到结果二维数组res中。
|
||||
注:实现的时候我们可以将path和res设置成全局的,免得传参。
|
||||
|
||||
相当于遍历一遍二叉树,所以时空复杂度均为O(n)
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
class Solution {
|
||||
@ -12,24 +14,20 @@ private:
|
||||
vector<int>path;
|
||||
vector<vector<int>>res;
|
||||
void helper(TreeNode *root, int sum){
|
||||
if(root == NULL) return;
|
||||
if(root -> val == sum && (!root->left) && (!root -> right)){ // 满足条件
|
||||
path.push_back(root -> val);
|
||||
res.push_back(path);
|
||||
path.pop_back();
|
||||
return;
|
||||
}
|
||||
path.push_back(root -> val);
|
||||
sum -= root -> val;
|
||||
helper(root -> left, sum);
|
||||
helper(root -> right, sum);
|
||||
path.pop_back(); // 注意离开前要将当前节点移除
|
||||
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();
|
||||
helper(root, sum);
|
||||
path.clear(); res.clear();
|
||||
if(root) helper(root, sum);
|
||||
return res;
|
||||
}
|
||||
};
|
||||
|
Loading…
Reference in New Issue
Block a user