class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
List<Integer> list = new ArrayList<>();
helper(res, list, root, sum);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> list, TreeNode root, int sum){
list.add(root.val);
if(root.left == null && root.right == null){
if(root.val == sum)
res.add(new ArrayList<>(list));
}
if(root.left != null)
helper(res, list, root.left, sum-root.val);
if(root.right != null)
helper(res, list, root.right, sum-root.val);
list.remove(list.size()-1);
}
}
I am working on Leetcode 113. Path Sum II. It's not about the problem itself. I want to know why I have to write res.add(new ArrayList<>(list)); instead of writing res.add(list); directly in line 13.
Writing new ArrayList<>(list) creates a new list, containing all the elements in list. This is required, since at the end of the function you are calling list.remove(list.size()-1);, you are thus modifying the list variable.
If you were to add list directly in res, the remove call would also modify res.
Another relevant example:
class MyClass {
public int modify = 5;
}
class Test {
public static void myFunction() {
MyClass object = new MyClass();
System.out.println(object.modify); // prints 5.
ArrayList<MyClass> myList = new ArrayList<>();
myList.add(object);
object.modify = 800;
for(MyClass item : myList) {
System.out.println(item.modify); // prints 800.
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With