I am solving a coding question where we need to remove all the sub-trees of a binary tree that only has 0 as its value . Question link https://leetcode.com/problems/binary-tree-pruning/ The solution that worked for me is this
public TreeNode pruneTree(TreeNode root) {
if (root == null)
return null;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if (root.val == 0 && root.left == null && root.right == null)
root = null;
else
return root;
// pruneTree1(root);
// printTree(root);
return root;
}
The solution I tried submitting earlier was this
public TreeNode pruneTree(TreeNode root) {
pruneTree1(root);
return root;
}
TreeNode pruneTree1 (TreeNode root) {
if(root ==null)
return root ;
root.left = pruneTree1(root.left);
root.right = pruneTree1(root.right);
if(root.left==null && root.right==null && root.val==0) {
System.out.println(root.val);
root =null;
}
return root;
}
My question/doubt is why the second solution wasn't changing the original tree. My understanding was Java is pass by value but when we pass an Object by its variable name its a reference to original object and we can change its content.
Why was it not working in this case. Is it because I am trying to set the whole object as null and not just its value ?
I tired recreating the scenario with another example and the code behaves differently in this case . Here's what i tried
public void run1() {
TreeNode root = new TreeNode();
root.val = 2;
TreeNode left = new TreeNode();
left.val = 3;
TreeNode right = new TreeNode();
right.val = 4;
TreeNode leftLeft = new TreeNode();
leftLeft.val = 5;
TreeNode rightRight = new TreeNode();
rightRight.val = 6;
root.left = left;
root.right = right;
left.left = leftLeft;
right.right = rightRight;
System.out.println(root.left.left.val);
TreeNode root2 = makeNull(root);
System.out.println(root.left.left);
System.out.println(root2.left.left);
};
public TreeNode makeNull (TreeNode root){
if(root ==null)
return root ;
root.left = makeNull(root.left);
root.right = makeNull(root.right);
if(root.val==5)
root=null;
// left.left = null;
return root;
}
In the example i both root.left.left and root2.left.left is set as null when i print it . Why it acts like parameter is passed as reference in this case but not in the above example.