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);
}
}
}