深度优先搜索结合回溯的思路可以解决本题。
定义一个List来存放搜索路径上的节点值,当搜索到达某个叶子节点且路径总和满足题目要求时,将该路径对应的List放入记录答案的List中,并回溯;如此递归下去,直到所有路径都被遍历一次。
class Solution {
List<List<Integer>> res;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
res = new ArrayList<>();
if(root == null)
return res;
dfs(root, sum, 0, new ArrayList<>());
return res;
}
private void dfs(TreeNode x, int sum, int curSum, List<Integer> paths){
paths.add(x.val);
curSum += x.val;
if(x.left == null && x.right == null){
if(curSum == sum){
res.add(new ArrayList<>(paths));
}
paths.remove(paths.size() - 1);
return;
}
if(x.left != null)
dfs(x.left, sum, curSum, paths);
if(x.right != null)
dfs(x.right, sum, curSum, paths);
paths.remove(paths.size() - 1);
}
}