LeetCode_Path Sum II

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 &currentSum){
            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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值