题目:输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
(注意: 在返回值的list中,数组长度大的数组靠前)
解析:
①从根节点开始递归访问左子树同时将给出的整数减去访问的结点值,当叶子结点的值等于剩余整数时,说明该路径满足条件,将其保存到List中;
②不管满不满足条件,都对访问过的结点后退一步,访问当前结点的下一叶子结点继续寻找其他路径;
③同样的操作访问根节点的右子树;
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> List = new ArrayList<>();
ArrayList<Integer> path = new ArrayList<>();
AllPath(root,target,path,List);//将满足所有路径和为target的存入
Collections.sort(List, new Comparator<ArrayList<Integer>>(){
@Override
public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
if (o1.size() < o2.size()){
return 1;//正数交换位置,负数不交换位置,o1<o2,交换位置--->o2 o1 降序
}
return -1;
}
});
return List;
}
public void AllPath(TreeNode root,int target,ArrayList<Integer> path,ArrayList<ArrayList<Integer>> List){
if (root == null) return;
path.add(root.val);//将从根节点开始到到叶子结点的路径的值加入ArrayList中
if (target==root.val&&root.left==null&&root.right==null){
//path只是一个引用,ArrayList(Collection<? extends E> c)
List.add(new ArrayList<Integer>(path));//这才是添加一个集合到List中
}else{
AllPath(root.left,target-root.val,path,List);//递归到root的左子树
AllPath(root.right,target-root.val,path,List);//递归到root的右子树
}
path.remove(path.size()-1);//如果没有当前路径没有找到,需要后退一个节点继续找(长度-1)
}