思路
回溯法。
时间复杂度O(n),空间复杂度O(n)。
代码
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
private ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
private ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null) return lists;
list.add(root.val);
target -= root.val;
if(target == 0 && root.left == null && root.right == null) {
lists.add(new ArrayList<Integer>(list));
} else {
FindPath(root.left, target);
FindPath(root.right, target);
}
list.remove(list.size()-1);
return lists;
}
}