LeetCode 113.路径总和II

题目链接 113.路径总和II
前序遍历
path更新过程:
[5,]
[5,4]
[5,4,11]
[5,4,11,7]
因为7是叶子节点,travesal(root.left, count);travesal(root.right, count);均在遇到if (root == null) return;后就返回了,所以回溯
[5,4,11]
[5,4,11,2]添加到result中
回溯
[5,4,11]
回溯
[5,4]
回溯
[5]
[5,8]
[5,8,3]
回溯
[5,8,4]
[5,8,4,5]添加到result中
回溯
[5,8,4]
[5,8,4,1]
遍历结束

// 解法2
class Solution {
    List<List<Integer>> result;
    LinkedList<Integer> path;
    public List<List<Integer>> pathSum (TreeNode root,int targetSum) {
        result = new LinkedList<>();
        path = new LinkedList<>();
        travesal(root, targetSum);
        return result;
    }
    private void travesal(TreeNode root,  int count) {
        if (root == null) return;
        path.offer(root.val);
        count -= root.val;
        if (root.left == null && root.right == null && count == 0) {
            result.add(new LinkedList<>(path));
        }
        travesal(root.left, count);
        travesal(root.right, count);
        path.removeLast(); // 回溯
    }
}

需要注意,这里的path 和 result都是LinkedList来存储,以便path使用removeLast方法删除最后一个元素。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

疯狂java杰尼龟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值