剑指offer(24)二叉树中和为某一值的路径
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
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 || target <= 0){
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);
Collections.sort(listAll, new Comparator<ArrayList<Integer>>(){
@Override
public int compare(ArrayList<Integer> o1 , ArrayList<Integer> o2){
return o2.size() - o1.size();
}
});
return listAll;
}
}