1

When I use res.add(temp), it gives empty lists as result, but when I use res.add(new ArrayList<Integer>(temp)), I get the right answer. Please explain why that happens.

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res=new ArrayList<>();
        check(root,targetSum,new ArrayList<>(),res);
        return res;
    }
    public void check(TreeNode root,int target,List<Integer> temp,List<List<Integer>>res)
    {
        if(root==null)
            return;
        if(root.left==null&&root.right==null&&target==root.val)
        {
            temp.add(root.val);
            **res.add(temp)**; //This is providing empty lists

            //**res.add(new ArrayList(temp)); This gives me the required result. But 
            //what is the difference between two.**

            temp.remove(temp.size()-1);
            return;
        }
        temp.add(root.val);
        check(root.left,target-root.val,temp,res);
        check(root.right,target-root.val,temp,res);
        temp.remove(temp.size()-1);
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    Because immediately after the adding you remove the last added element from the list again with `temp.remove(temp.size()-1);` so temp will be empty. `new ArrayList(temp)` is using the copy constructor and creating a new shallow copy of temp. Since you don't remove anything from that shallow copy it will not be empty. – OH GOD SPIDERS Aug 04 '21 at 14:15
  • Thank you! I just want to know when i was using res.add(temp). So, does that mean i was adding reference to the same memory location(temp) to my res again and again? – Piyush Pawar Aug 04 '21 at 15:50
  • 1
    Yes, that's exactly it. In your non-working version you had a list where all elements pointed to the exact same same list `temp` in the memory. While in the working version as mentioned you create a new copy of temp and add that copy to your list. – OH GOD SPIDERS Aug 04 '21 at 15:56

0 Answers0