题目描述


题解
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<Integer> path = new ArrayList<Integer>();
recur(root, sum, path);
return res;
}
private void recur(TreeNode root, int target, ArrayList<Integer> path) {
if (root == null)
return;
path.add(root.val);
target -= root.val;
if ((target == 0) && (root.left == null) && (root.right == null))
res.add(new ArrayList<>(path));
else {
recur(root.left, target, path);
recur(root.right, target, path);
}
path.remove(path.size() - 1);
}
}
import java.util.ArrayList;
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<Integer> path = new ArrayList<>();
recur(root, target, path);
return res;
}
private void recur(TreeNode root, int target, ArrayList<Integer> path) {
if (root == null)
return;
target -= root.val;
path.add(root.val);;
if ((target == 0) && (root.left == null) && (root.right == null))
res.add(new ArrayList<>(path));
else {
recur(root.left, target, path);
recur(root.right, target, path);
}
path.remove(path.size() - 1);
}
}