【LeetCode笔记】112 & 113. 路径总和 I & II(Java、递归、DFS)

比较简单,就连着一起写了

路径总和 I

  • 注意:一定得走到叶子才算
    在这里插入图片描述
  • 直接看代码吧,注释也就几行。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // 递归解决战斗
    public boolean hasPathSum(TreeNode root, int targetSum) {
        // 递归结束条件
        if(root == null){
            return false;
        }
        // 找到结果条件
        if(targetSum == root.val && root.left == null && root.right == null){
            return true;
        }
        // 往左右继续递归
        return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
    }
}

路径总和 II

  • 相当于在 I 的基础上,加入了一个路径的存储、修改
    在这里插入图片描述
  • 注意。。存储的路径要 new 出来再存入
class Solution {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        find(root, targetSum);
        return ans;
    }
    void find(TreeNode root, int targetSum){
        // 递归结束条件
        if(root == null){
            return;
        }
        // 路径在递归前后进行增减
        path.add(root.val);
        // 找到答案的情况
        if(targetSum == root.val && root.left == null && root.right == null){
            ans.add(new LinkedList<>(path));
        }
        find(root.left, targetSum - root.val);
        find(root.right, targetSum - root.val);
        path.removeLast();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值