diff --git a/solutions/113. Path Sum II.md b/solutions/113. Path Sum II.md new file mode 100644 index 0000000..22d48b2 --- /dev/null +++ b/solutions/113. Path Sum II.md @@ -0,0 +1,36 @@ +# [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: + vectorpath; + vector>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> pathSum(TreeNode* root, int sum) { + path.clear(); + res.clear(); + helper(root, sum); + return res; + } +}; +```