思路:回溯
代码:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
// write code here
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
backtrack(root, res, sum, path);
return res;
}
public void backtrack(TreeNode root, ArrayList<ArrayList<Integer>> res, int sum, List<Integer> path) {
if (root == null) {
return;
}
if (root != null && root.left == null && root.right == null) {
if (sum - root.val == 0) {
path.add(root.val);
res.add(new ArrayList(path));
path.remove(path.size() - 1);
}
return;
}
path.add(root.val);
backtrack(root.left, res, sum - root.val, path);
backtrack(root.right, res, sum - root.val, path);
path.remove(path.size() - 1);
}
}