LeetCode—112. Path Sum && 113. Path Sum II

LeetCode—112. Path Sum

题目

https://leetcode.com/problems/path-sum/description/

给出一棵二叉树以及一个整数,判断有没有一条从树的根节点到叶子节点的路径,其路径上节点的和等于给出的整数。
https://leetcode.com/problems/path-sum-ii/description/
返回满足条件的所有路径。

在这里插入图片描述

在这里插入图片描述

思路及解法

首先肯定是要用到递归了。
在来想递归条件。每次递归一个节点,都从给出的整数里减去这个节点的值,直到最后一个不为空的叶子节点。
每一个父节点而言,左右两个子节点递归只要有一个满足即可。
若是两个子节点都为空,那么需要判断父节点是否等于最终的结果。
若是遍历到节点本身是空的,说明之前遍历的结果没有返回true,所以到这里就返回false

整体的框架和上一道题一样。
需要建立一个tmp列表来保存当前走过的路径,递归完后需要把最后一个元素remove。需要注意的是,tmp传递的是一个引用,将tmp加入到res中时,需要new一个新的列表,不然res会随着tmp的变化而变化,导致结果出错。

代码
/**
 * 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;
        if(root.left==null && root.right==null){
            return root.val==sum;
        }
        return hasPathSum(root.left, sum-root.val) 
               || hasPathSum(root.right, sum-root.val);
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {       
        List<Integer> tmp = new ArrayList<>();
        DFS(tmp, root, sum);
        return res;
    }
    public void DFS(List<Integer> tmp, TreeNode node, int sum){       
        if(node==null) return;
        // System.out.println("res:"+res);
        sum -= node.val;
        tmp.add(node.val);
        // System.out.println("0:"+tmp);
        if(node.left==null && node.right==null){ //递归结束条件
            if(sum==0){
                // System.out.println("1:"+tmp);
                // System.out.println("1:"+res);
                res.add(new ArrayList<>(tmp));  //一定要new,直接用tmp错。我感觉是因为tmp只是在传递一个引用
                // System.out.println("2:"+tmp);
                // System.out.println("2:"+res);
            }
                
            tmp.remove(tmp.size()-1);
            return;
        }else{          
            DFS(tmp, node.left, sum);
            DFS(tmp, node.right, sum);
            tmp.remove(tmp.size()-1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值