Need help in understanding Java pass by reference in recursive calls.

I have seen this issue happen with one or two leetcode problems. I am running into issue where when i make edits to objects via recursive call, the parent function does still retains reference to the old value. This does not seem to be the case when you actually make edits to the parent function and pass it down to the child. Can anyone explain this behavior better? or Any documentation on it? How would you proceed if you end up in this situation? Let me show an example.

The problem is about deleting all nodes in to_delete and returning the forst as a list.
ref problem: https://leetcode.com/problems/delete-nodes-and-return-forest/
Here is my code.

class Solution {
	public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
		List<TreeNode> list = new LinkedList<TreeNode>();
		HashSet<Integer> set = new HashSet<Integer>();
		for(int i=0;i<to_delete.length;i++) set.add(to_delete[i]);
		delNodes(list,root,set);
		list.add(root);
		return list;
	}
	public void delNodes(List<TreeNode> list, TreeNode root, HashSet<Integer> set) {
		if(root == null) return;
		delNodes(list,root.left,set);
		delNodes(list,root.right,set);
		if(set.contains(root.val)) {
			if(root.left!=null) list.add(root.left);
			if(root.right!=null) list.add(root.right);
			root = null;
		}

	}
}

For the example. if i try with the test case.

Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[6],[7],[1,2,3,4,5,6,7]]
Expected: [[1,2,null,null,5],[6],[7]]

The expected and output does not match even though i changed the root value of 3 and 5 to null. Why does java still retain reference to the old object?

Comments (0)