1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) { ArrayList<ArrayList<Integer>> paths = new ArrayList<>(); ArrayList<Integer> path = new ArrayList<>();
FindPath(root, target, 0, path, paths);
return paths; }
private void FindPath(TreeNode root, int target, int sum, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> paths) { if (root == null) return;
int currentSum = sum + root.val; path.add(root.val);
if (currentSum == target && root.left == null && root.right == null) paths.add(new ArrayList(path));
FindPath(root.left, target, currentSum, path, paths); FindPath(root.right, target, currentSum, path, paths);
path.remove(path.size() - 1); }
|
近期评论