二叉树中和为某一值的路径
二叉树中和为某一值的路径
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的 list 中,数组长度大的数组靠前)
import java.util.*;
public class Solution {
ArrayList<ArrayList<Integer>>ans=new ArrayList<ArrayList<Integer>>();
Stack<Integer>path=new Stack();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
if(root==null){
return ans;
}
find(root,target,0);
ans.sort(new Comparator<ArrayList<Integer>>(){
@Override
public int compare(ArrayList<Integer>array1,ArrayList<Integer>array2){
if(array1.size()<array2.size()){
return 1;
}else
return -1;
}
});
return ans;
}
private void find(TreeNode root,int target,int now){
if(target==now&&root==null){
ans.add(new ArrayList<Integer>(path));
return ;
}
if(root==null){
return;
}
path.push(root.val);
find(root.left,target,now+root.val);
if(root.left==null&&root.right==null){
path.pop();
return;
}
find(root.right,target,now+root.val);
path.pop();
}
}
要点:
-
对容器进行排序的方法:https://www.cnblogs.com/jiading/articles/12418987.html
-
注意容器的默认排序规则是升序,也就是小的在前
-
注意Comparator也要加泛型:
Comparator c=new Comparator<ArrayList<Integer>>(){ -
注意写Comparator时候的规则:
Comparator c=new Comparator<ArrayList<Integer>>(){ @Override public int compare(ArrayList<Integer>x,ArrayList<Integer>y){ if(x.size()>y.size()){ return -1; } else return 1; }我们想要降序,就要让x>y的输出为负

浙公网安备 33010602011771号