[leetcode]Path Sum II
2015-03-17 15:15
423 查看
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
DFS,当搜索到叶子节点时把路径存储下来。
DFS,当搜索到叶子节点时把路径存储下来。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool ans = false; vector<int> st; vector<vector<int>> v; vector<vector<int> > pathSum(TreeNode *root, int sum) { if(root == NULL) return v; st.push_back(root->val); if(root->left == NULL && root->right == NULL){ int a = 0; for(int i=0;i<st.size();i++){ a += st[i]; } ans = (a==sum); if(ans){ vector<int> ve; for(int i=0;i<st.size();i++){ ve.push_back(st[i]); } v.push_back(ve); } return v; } pathSum(root->left,sum); if(root->left != NULL) st.erase(st.end()-1); pathSum(root->right,sum); if(root->right != NULL) st.erase(st.end()-1); return v; } };
相关文章推荐
- [Leetcode]Path Sum II
- [LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
- 【LeetCode with Python】 Path Sum II
- Leetcode-113. Path Sum II
- [leetcode] Path Sum II
- #leetcode#Path Sum II
- Leetcode:Path Sum II
- [leetcode]Path Sum II
- [LeetCode] Path Sum II
- LeetCode 113: Path Sum II 二叉树遍历
- leetcode — path-sum-ii
- (面试题25题)LeetCode Path Sum II
- leetcode 113. Path Sum II
- [LeetCode] Path Sum II 解题报告
- LeetCode | Path Sum II
- LeetCode_Path Sum II
- leetcode Path Sum II
- Leetcode Path Sum II
- 【LeetCode】Path Sum II
- [LeetCode] Path Sum II 深度搜索