leetcode113

https://leetcode.cn/problems/path-sum-ii

点击查看代码
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
          List<List<Integer>> ans = new ArrayList<>();
          List<Integer> path = new ArrayList<>();
          preorder(ans,path,root,targetSum);
          return ans;
    }
    void preorder(List<List<Integer>> ans,List<Integer> path,TreeNode root,int targetSum){
        if(root==null) return;
        path.add(root.val);
        if(root.left==null&&root.right==null){
           if(targetSum-root.val==0){
            ans.add(new ArrayList<>(path));
           }
        }
        preorder(ans,path,root.left,targetSum-root.val);
        preorder(ans,path,root.right,targetSum-root.val);
        path.remove(path.size()-1);
    }
}

递归三部曲:

1.参数和返回值。
2.终止条件。当前节点为叶子节点时终止。我的写法在递归调用时没有判断null,所以每层增加一个root==null?的判断。
3.单层逻辑。当前节点为叶子节点,且节点的val等于target则添到ans中。

本题的小坑在于ans.add(new ArrayList<>(path));写成ans.add(path)。path指向的都是同一个引用,导致ans中添加的list都是同一个。因此需要每次添加new一个path。

posted @ 2024-03-24 22:44  taolll  阅读(13)  评论(0)    收藏  举报