Please help me understand the difference. Like in first code snippet, I'm passing the updated ArrayList as a parameter in the recursive function in Line 1 & 2. This is giving me wrong answer.
public static void rootToLeafPaths(TreeNode node, ArrayList<Integer> sub){
if(node == null)
return;
sub.add(node.val);
if(node.left == null && node.right == null){
list.add(sub);
return;
}
rootToLeafPaths(node.left,sub); //LINE 1
rootToLeafPaths(node.right,sub); //LINE 2
sub.remove(sub.size()-1);
}
In the second code snippet I'm passing a newly created ArrayList(in Line 3 & 4) which is giving me the correct answer.
public static void rootToLeafPaths(TreeNode node, ArrayList<Integer> sub){
if(node == null)
return;
sub.add(node.val);
if(node.left == null && node.right == null){
list.add(sub);
return;
}
rootToLeafPaths(node.left,new ArrayList<Integer> (sub)); // LINE 3
rootToLeafPaths(node.right,new ArrayList<Integer> (sub)); // LINE 4
sub.remove(sub.size()-1);
}
Help me understand the difference.
This method is supposed to provide the root to leaf paths of a binary tree. Like in first case it is giving me [[1, 2, 4], [1, 2, 4], [1, 2, 4]] as output which is wrong, but when I'm passing a newly created ArrayList each time it is giving me [[1, 2, 4, 6, 8], [1, 2, 5, 7, 9, 10], [1, 3]] as output which is correct
Short Summary(Based on answers): Even if we assign list to some other list(Example: List list = list2), we're assigning the reference to it. So both will be pointing to same list. And changes in one will be reflected in another. So to solve this we'll need to create another list by (List list = new ArrayList(list2);)