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);
}
}