Leetcode Path Sum II
2013-12-06 14:20
295 查看
dfs,跟Path Sum I 相差无几。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
ans.clear();
dfs(root, sum, 0);
return ans;
}
void dfs(TreeNode *root, int sum, int cnt){
if(!root) return ;
if(!root->left && !root->right){
if(cnt + root->val == sum){
v.push_back(root->val);
ans.push_back(v);
v.pop_back();
}
return ;
}
v.push_back(root->val);
dfs(root->left, sum, cnt+root->val);
dfs(root->right, sum, cnt+root->val);
v.pop_back();
}
vector<int> v;
vector<vector<int> > ans;
};
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
ans.clear();
dfs(root, sum, 0);
return ans;
}
void dfs(TreeNode *root, int sum, int cnt){
if(!root) return ;
if(!root->left && !root->right){
if(cnt + root->val == sum){
v.push_back(root->val);
ans.push_back(v);
v.pop_back();
}
return ;
}
v.push_back(root->val);
dfs(root->left, sum, cnt+root->val);
dfs(root->right, sum, cnt+root->val);
v.pop_back();
}
vector<int> v;
vector<vector<int> > ans;
};
相关文章推荐
- [LeetCode] Path Sum II
- LeetCode113:Path Sum II
- leetcode -- Path Sum II
- leetcode || 113、Path Sum II
- LeetCode 112, 123. Path Sum i, ii
- LeetCode113 Path Sum II
- LeetCode - Path Sum II
- [LeetCode] Path Sum II
- *LeetCode-Path Sum II
- Path Sum II -- LeetCode
- leetcode 刷题之路 66 Path Sum II
- LeetCode Path Sum II
- 【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 113. Path Sum II(路径和)
- LeetCode刷题(C++)——Path Sum II(Medium)