Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
这道题和他的兄弟题目一样,都是DFS,但是我很困惑的是我的代码MLE,于是看了http://www.cnblogs.com/remlostime/archive/2012/11/13/2767760.html上的代码,发现我们的代码惊人的相似,但是他的AC了,郁闷,谁要是知道为什么?求讲解。
我的代码:
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector <vector <int>> result;
vector <int> path;
int currentSum=0;
pathSum(root,sum,result,path,currentSum);
return result;
}
//Memory Limit Exceed
void pathSum(TreeNode *root,const int &sum,vector<vector<int>> &res,
vector <int> &path,int ¤tSum){
if(root==NULL){
return;
}
path.push_back(root->val);
//还没达到叶节点
currentSum+=root->val;
if (root->left!=NULL||root->right!=NULL){
pathSum(root->left,sum,res,path,currentSum);
pathSum(root->left,sum,res,path,currentSum);
}
else{
if(currentSum==sum){
res.push_back(path);
}
}
currentSum-=root->val;
path.pop_back();
}
};
AC代码:
class Solution {
private:
vector<vector<int> > ret;
public:
void dfs(TreeNode *node, int sum, int curSum, vector<int> a)
{
if (node == NULL)
return;
if (node->left == NULL && node->right == NULL)
{
if (curSum + node->val == sum)
{
a.push_back(node->val);
ret.push_back(a);
}
return;
}
a.push_back(node->val);
dfs(node->left, sum, curSum + node->val, a);
dfs(node->right, sum, curSum + node->val, a);
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ret.clear();
vector<int> a;
dfs(root, sum, 0, a);
return ret;
}
};
My Submissions for Path Sum II
Submit Time | Status | Run Time | Language |
---|---|---|---|
14 minutes ago | Accepted | 108 ms | cpp |
18 minutes ago | Memory Limit Exceeded | N/A | cpp |
19 minutes ago | Compile Error | N/A | cpp |
24 minutes ago | Memory Limit Exceeded | N/A | cpp |