mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
37 lines
1.3 KiB
Markdown
37 lines
1.3 KiB
Markdown
![]() |
# [113. Path Sum II](https://leetcode.com/problems/path-sum-ii/)
|
|||
|
# 思路
|
|||
|
给定一棵二叉树,求所有根到叶子路径中和为sum的路径。
|
|||
|
考虑用DFS,遍历的时候用一维数组path记录当前经过的路径,每遍历一个节点就将其加入path,从这个结点返回时,需要把该节点从path中移除。如果当前节点是叶子节点而且
|
|||
|
满足和为sum,即可将path加入到结果二维数组res中。
|
|||
|
注:实现的时候我们可以将path和res设置成全局的,免得传参。
|
|||
|
|
|||
|
# C++
|
|||
|
``` C++
|
|||
|
class Solution {
|
|||
|
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(); // 注意离开前要将当前节点移除
|
|||
|
}
|
|||
|
public:
|
|||
|
vector<vector<int>> pathSum(TreeNode* root, int sum) {
|
|||
|
path.clear();
|
|||
|
res.clear();
|
|||
|
helper(root, sum);
|
|||
|
return res;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|