Leetcode 113 Path Sum II

Leetcode 113 Path Sum II

思路

思路:首先对树进行前序遍历,在遍历的同时将路径、路径和都记录下来,然后在叶子节点的地方进行判断当前路径和与要求是否匹配,若匹配则将当前路径添加到list中。在一个节点遍历完了之后,需要将当前节点从临时路径tmp中删除。

复杂度分析

时间复杂度O(n)
空间复杂度O(n)

代码

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        // the 2rd time
        List<List<Integer>> res = new ArrayList<>();
        if(root == null)
            return res;
        List<Integer> tmp = new ArrayList<>();
        preorder(res,tmp,root,sum);
        return res;
    }
    
    public void preorder(List<List<Integer>> res,List<Integer> tmp,
                        TreeNode root,int sum){
        // base case:
        if(root == null)
            return;
        tmp.add(root.val);
        // if the current node is a leaf and the sum is satisfied
        if(root.left == null && root.right == null && sum == root.val){
            res.add(new ArrayList<>(tmp));
        }
        preorder(res,tmp,root.left,sum-root.val);
        preorder(res,tmp,root.right,sum-root.val);
        tmp.remove(tmp.size()-1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值