20200410:路径总和 Ⅰ&& Ⅱ(leetcode112 /113)

题目

在这里插入图片描述

在这里插入图片描述

思路与算法

  1. 112题很容易,相当这是一个简单的DFS问题。

  2. 112题的递归边界条件为:

    Ⅰ root为null。
    Ⅱ root的左右子树为null。
    
  3. 113题是对输出做了改变,整体思路是一致的。

  4. 我们需要同时记录当前访问的节点并保存他,边界条件是一致的。

代码实现

112:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null){
            return false;
        }

        sum -= root.val;
        if(root.left == null && root.right == null) {
            return (sum == 0);
        }
        return hasPathSum(root.left,sum) || hasPathSum(root.right,sum);
    }
}

113:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    public List<List<Integer>> pathSum(TreeNode root, int sum) {

        // 新建结果集
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        // 双端队列来存放对应的路径数组
        Deque<Integer> path = new ArrayDeque<>();
        pathSum(root, sum, path, res);
        return res;
    }

    public void pathSum(TreeNode node, int sum, Deque<Integer> path, List<List<Integer>> res) {

        // 递归边界条件
        if (node == null) {
            return;
        }

        // 从当前sum中减去当前节点的值,再将减去的这个节点值添加到path队列存放
        sum -= node.val;
        path.addLast(node.val);
        
        if (sum == 0 && node.left == null && node.right == null) {
            // 存放到res结果集中
            res.add(new ArrayList<>(path));
            // 清空path
            path.removeLast();
            return;
        }

        pathSum(node.left, sum, path, res);
        pathSum(node.right, sum, path, res);
        // 递归完成以后,再次清空
        path.removeLast();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

IMMUNIZE

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

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

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

打赏作者

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

抵扣说明:

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

余额充值