Path Sum II

本题目要保存所有符合条件的路径,用广搜的话空间占用会非常大。递归深搜是较好的方法,碰到根节点则做判断,如果路径的和符合条件,则保存该路径。回溯时记得从路径中减去当前节点。时间复杂度O(n),空间O(logN)。

class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        
        vector<vector<int> > result;
        vector<int> tmp;
        if(root == NULL) return result;
        pathSum(root, sum, tmp, result);
    }
    
    void pathSum(TreeNode *root, int gap, vector<int> &path, vector<vector<int> > &result)
    {
        path.push_back(root->val);
        if(root->left == NULL && root->right == NULL && root->val == gap)
        {
            vector<int> p(path.begin(), path.end());
            result.push_back(p);
        }
        if(root->left) 
            pathSum(root->left, gap-root->val, path, result);
        if(root->right)
            pathSum(root->right, gap-root->val, path, result);
            
        path.pop_back();
    }
};


Method 2: iterative DFS using stack (postorder)     http://blog.csdn.net/starmsg/article/details/39030379

class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > result;
        vector<int> path;
        
        if(root == NULL) return result;
        stack<TreeNode*> stack;
        TreeNode *cur = root, *prev = NULL;
        
        int value = 0;
        while(!stack.empty() || cur != NULL) 
        {
            
            if(cur != NULL)
            {
                stack.push(cur);
                path.push_back(cur->val);
                value += (cur->val);
                cur = cur->left;
            }
            else
            {
                cur =  stack.top();
                if(cur->right == NULL || cur->right == prev)
                {
                    //visit
                    if(cur->left == NULL && cur->right == NULL && value == sum)
                        result.push_back(path);
                        
                    path.pop_back();
                    value -= cur->val;
                    stack.pop();
                    prev = cur;
                    cur = NULL;
                }
                else
                    cur = cur->right;
            }
        }
        return result;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值