题目描述 :
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
这个题目没什么新颖的,先分析一下再说一下我想到的细节
我先摘抄一份大神的代码,来自https://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca?f=discussion
public class Solution {
private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
private ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null) return listAll;
list.add(root.val);
target -= root.val;
if(target == 0 && root.left == null && root.right == null)
listAll.add(new ArrayList<Integer>(list));
FindPath(root.left, target);
FindPath(root.right, target);
list.remove(list.size()-1);
return listAll;
}
}
就是遍历,看到
FindPath(root.left, target);
FindPath(root.right, target);
就知道是深度优先,每一个都路径都记录在list
集合里,当达到要求时就以当前的list集合为标准创建一个新的list集合添加到listAll里,而返回父节点时把旧的list集合里最后一个数据删除,因为它是当前节点的,下一次用不到它了,就相当于回到父节点转弯到右节点
这个想法很新颖,这样所有的叶子节点都可以遍历到(但也存在浪费的问题),下面分析一下啊
1、是否可以在某个地方剪支呢?
这个题目没有告诉我们这个二叉树里面的值是否为正和为负,所以下面的只是分析一下,不是让大家照着下面的写,因为出题人如果有负值人家也没错
如果此二叉树只有正值或者是0,没有负值,那我们是不是可以添加一个判断呢?这样就不用到所有的叶子节点了,就像我知道到这个节点再往下肯定和大于目标值,就不往下走了,回去
下面是
public class Main {
ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root ==null) {
return listAll;
}
list.add(root.val);
if(target - root.val>0) {
FindPath(root.left, target - root.val);
FindPath(root.right, target - root.val);
}
if(target - root.val ==0&&root.left==null&&root.right==null) {
listAll.add(new ArrayList<Integer>(list));
}
list.remove(list.size()-1);
return listAll;
}
}
2、最后得出来的listAll 到底需要排序吗?
因为题意没给是什么二叉树,那我可不可以想法极端一些的,因为深度遍历,我就让前面的长度尽可能的大,后面的长度尽可能的小(这个是很有可能的,我也建议大家尽量输出前排一下序)
下面这样我感觉是最完美的,题意完美契合
public class Main {
ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
FindPath1(root, target);
//自定义集合排序
Comparator<ArrayList<Integer>> c = new Comparator<ArrayList<Integer>>() {
@Override
public int compare(ArrayList<Integer> o1,ArrayList<Integer> o2) {
//排序的规则,这是如果o1的长度大于o2的长度,那么o1就往后
if(o1.size()>o2.size()) {
return -1;
}else {
return 1;
}
}
};
//返回的listAll排序,下面这个和Collections.sort(List<T> list, Comparator<> c)是一样的功能
listAll.sort(c);;
return listAll;
}
public ArrayList<ArrayList<Integer>> FindPath1(TreeNode root,int target) {
if(root ==null) {
return listAll;
}
list.add(root.val);
if(target - root.val ==0&&root.left==null&&root.right==null) {
listAll.add(new ArrayList<Integer>(list));
}
FindPath1(root.left, target - root.val);
FindPath1(root.right, target - root.val);
list.remove(list.size()-1);
return listAll;
}
}