这题跟上个题的区别112. 路径总和,需要保存下路径,且有可能出现多条路径。
在前一个题的基础上加上回溯即可
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ansList = new ArrayList<>();
if (root == null) return ansList;
List<Integer> curList = new ArrayList<>();
findPath(root, sum, curList, ansList);
return ansList;
}
private void findPath(TreeNode root, int sum, List<Integer> curList, List<List<Integer>> ansList) {
if (root == null) return;
curList.add(root.val);
if (root.left == null && root.right == null && sum == root.val) {
List<Integer> tmp = new ArrayList<>(curList);
ansList.add(tmp);
} else {
findPath(root.left, sum - root.val, curList, ansList);
findPath(root.right, sum - root.val, curList, ansList);
}
curList.remove(curList.size() - 1);
}
}