I have encountered several places while solving problems using recursion and lists that the results change drastically, when a deep copy of list is passed vs shallow copy. For example, in the code snippet below (to print all root to leaf paths in a binary tree), passing the shallow copy of the list in the left and right subtree recursive calls, gives incorrect results. While passing a deep copy works as expected.
Can anyone explain what's the difference between the two and specifically, how it makes a difference in recursion.
Thanks in advance !
List<List<Integer>> result = new ArrayList();
public void getPath(TreeNode root, List<Integer> path) {
if(root == null)
return;
path.add(root.val);
if(root.left == null && root.right == null) {
this.result.add(path);
return;
}
else {
getPath(root.left, new ArrayList(path));
getPath(root.right, new ArrayList(path));
//getPath(root.left, path);
//getPath(root.right, path);
}
}