思路:
带着sum去遍历二叉树,将每一个节点先加进来,不合适就回溯,找到路径加入到结果集当中;
- 每一步递归要完成:将节点加入,更新目标值
- 递归出口:到底部,node==null
- 加上回溯
代码:
class Solution {
LinkedList<List<Integer>> res=new LinkedList<>();
LinkedList<Integer> path=new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
rec(root,sum);
return res;
}
public void rec(TreeNode root,int target){
if(root==null){
return;
}
path.add(root.val);
target-=root.val;
if(target==0&&root.right==null&&root.left==null){
res.add(new LinkedList<>(path));
}
rec(root.left,target);
rec(root.right,target);
path.removeLast();
}
}