LeetCode:113. 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的解法加回溯,即从根节点到叶子的路径都遍历一遍,将符合的路径加入列表中。时间复杂度是O(n)。

class Solution {
    List<List<Integer>> res=new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if(root==null) return new ArrayList<>();
        List<Integer> ls=new ArrayList<>();
        dfs(ls,root,sum);
        return res;
    }
    public void dfs(List<Integer> ls,TreeNode node,int sum){
        ls.add(node.val);
        if(node.left==null&&node.right==null)
        {
            if(sum==node.val)
            {
                res.add(new ArrayList<Integer>(ls));
            }
            ls.remove(ls.size()-1);
            return;

        }
        if(node.left!=null)
            dfs(ls,node.left,sum-node.val);
        if(node.right!=null)
            dfs(ls,node.right,sum-node.val);
        ls.remove(ls.size()-1);

    }
}

二.扩展

因为是采用递归的方法,就很容易想到能不能用迭代的方法实现。然后试了一下,发现总是NA,后来参考了discussion板块的别人的解法后,我才知道了在回溯的时候要检查下一结点是否是之前遍历过的。时间复杂度O(n)。
这是原地址:
https://discuss.leetcode.com/topic/31698/java-solution-iterative-and-recursive/6

class Solution{
    public List<List<Integer>> pathSum(TreeNode root,int sum){
        List<List<Integer>> res=new ArrayList<>();
        if(root==null) return res;
        List<Integer> ls=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        TreeNode cur=root;
        TreeNode pre=null;
        int valsum=0;
        while(cur!=null||!stack.isEmpty())
        {
            while(cur!=null)
            {
                stack.push(cur);
                ls.add(cur.val);
                valsum+=cur.val;
                cur=cur.left;
            }
            cur=stack.peek();
            if(cur.right!=null&&cur.right!=pre)
            {
                cur=cur.right;
                continue;
            }
            if(cur.left==null&&cur.right==null&&valsum==sum)
                res.add(new ArrayList<Integer>(ls));
            stack.pop();
            valsum-=cur.val;
            ls.remove(ls.size()-1);
            pre=cur;
            cur=null;
        }
        return res;
    }
}

如果有什么错误或者是可以改进的地方,请大家积极指出,我会认真改进的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值