【又是回溯+遞歸】二叉樹路徑和

在這裏插入圖片描述
思路:
帶着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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章