113. Path Sum II [Medium]

还有iterative的方法,看起来很麻烦好像要用多个栈,回头可以学习一下

/**
 * 自己的代码,recursive
 * Runtime: 1 ms, faster than 99.94%
 * Memory Usage: 39.2 MB, less than 78.25%
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) // 是空节点
            return res;

        targetSum -= root.val;
        if (root.left == null && root.right == null) { // 是叶子节点
            if (targetSum == 0) {
                List curr = new ArrayList<>();
                curr.add(root.val);
                res.add(curr);
            }
            return res;        
        }

        res.addAll(pathSum(root.left, targetSum)); // 获取左子树所有有效路径
        res.addAll(pathSum(root.right, targetSum)); // 获取右子树所有有效路径
        for (List l : res)
            l.add(0, root.val); // 将当前节点的val加到每条路径中(注意要加在头部,即index为0)
        return res;
    }
}
/**
 * 用helper的recursive方法
 * 要注意对于所有递归共享的地址,每次修改都要用完了后改回去
 * Runtime: 1 ms, faster than 99.94%
 * Memory Usage: 38.9 MB, less than 95.52%
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new ArrayList<>();
        helper(root, targetSum, res, new ArrayList<>());
        return res;
    }

    private void helper(TreeNode root, int targetSum, List<List<Integer>> res, List<Integer> path) {
        if (root == null)
            return;
        targetSum -= root.val;
        path.add(root.val);
        if (root.left == null && root.right == null && targetSum == 0)
            res.add(new ArrayList(path)); // 不能直接add(path),因为path被所有递归共用,会不断被修改,要深拷贝一个path
        helper(root.left, targetSum, res, path);
        helper(root.right, targetSum, res, path);
        path.remove(path.size() - 1); // 所有递归里共用同一个path地址,所以每次修改path之后必须改回去
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值