代码如下:
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<Integer> path = new ArrayList<>();
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
helper(root, target, path, res);
Collections.sort(res, (o1, o2) -> o2.size() - o1.size());
return res;
}
private void helper(TreeNode root, int target, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> res) {
if(root == null){
return;
}
path.add(root.val);
target -= root.val;
if(root.left == null && root.right == null && target == 0){
res.add(new ArrayList<>(path));
}
helper(root.left, target, path, res);
helper(root.right, target, path, res);
path.remove(path.size() - 1);
}
}