思路:
帶着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();
}
}