LeetCode/solutions/113. Path Sum II.md
2019-05-31 23:38:32 +08:00

37 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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;
}
};
```