LeetCode/solutions/113. Path Sum II.md

35 lines
1.3 KiB
Markdown
Raw Normal View History

2019-05-31 15:38:32 +00:00
# [113. Path Sum II](https://leetcode.com/problems/path-sum-ii/)
# 思路
给定一棵二叉树求所有根到叶子路径中和为sum的路径。
考虑用DFS遍历的时候用一维数组path记录当前经过的路径每遍历一个节点就将其加入path从这个结点返回时需要把该节点从path中移除。如果当前节点是叶子节点而且
满足和为sum即可将path加入到结果二维数组res中。
实现的时候我们可以将path和res设置成全局的免得传参。
2020-02-07 02:52:28 +00:00
相当于遍历一遍二叉树所以时空复杂度均为O(n)
2019-05-31 15:38:32 +00:00
# C++
``` 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;
2020-02-07 02:52:28 +00:00
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();
2019-05-31 15:38:32 +00:00
}
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
2020-02-07 02:52:28 +00:00
path.clear(); res.clear();
if(root) helper(root, sum);
2019-05-31 15:38:32 +00:00
return res;
}
};
```