[Leetcode]Path Sum II
2015-01-27 06:35
267 查看
//DFS和二叉树
class Solution {
private:
vector<int>temp;
vector<vector<int>>result;
void solve_dfs(TreeNode *root,int sum,vector<int> temp,int add)
{
if(root==NULL)
return;
if(root->left==NULL&&root->right==NULL)
{
if(add+root->val==sum)
{
temp.push_back(root->val);
result.push_back(temp);
temp.clear();
}
return;
}
temp.push_back(root->val);
solve_dfs(root->left,sum,temp,add+root->val);
solve_dfs(root->right,sum,temp,add+root->val);
}
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
result.clear();
solve_dfs(root,sum,temp,0);
return result;
}
};
class Solution {
private:
vector<int>temp;
vector<vector<int>>result;
void solve_dfs(TreeNode *root,int sum,vector<int> temp,int add)
{
if(root==NULL)
return;
if(root->left==NULL&&root->right==NULL)
{
if(add+root->val==sum)
{
temp.push_back(root->val);
result.push_back(temp);
temp.clear();
}
return;
}
temp.push_back(root->val);
solve_dfs(root->left,sum,temp,add+root->val);
solve_dfs(root->right,sum,temp,add+root->val);
}
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
result.clear();
solve_dfs(root,sum,temp,0);
return result;
}
};
相关文章推荐
- Path Sum II (Find Path in Tree) -- LeetCode
- Leetcode Path sum II
- [leetcode] 113. Path Sum II
- LeetCode Path Sum II
- LeetCode--path sum ii
- LeetCode Path Sum II
- LeetCode 113. Path Sum II
- leetcode 113 Path Sum II
- 【LeetCode】112,113,437. Path Sum I, II, III
- [LeetCode]Path Sum II
- LeetCode113 Path Sum II
- LeetCode - Refresh - Path Sum II
- Leetcode-path-sum-ii
- *LeetCode-Path Sum II
- LeetCode: Path Sum II
- LeetCode OJ Path Sum II
- Leetcode: Path Sum II
- leetcode_113_Path Sum II
- leetcode:Path Sum II
- 【一天一道LeetCode】#113. Path Sum II