I'm trying to understand why my first implementation of addToTree()
doesn't work, but the second one does. I have commented the lines that are different:
public static void addToTree(Node n, int value){ //return type is void
if (n != null){
if (n.val >= value){
addToTree(n.left, value);
} else {
addToTree(n.right, value);
}
} else {
n = new Node(value);
}
}
Here is the implementation that actually works:
public static Node addToTree(Node n, int value){ //return type is Node
if (n != null){
if (n.val >= value){
n.left = addToTree(n.left, value); //sets n.left with the return value
} else {
n.right = addToTree(n.right, value); //sets n.right with the return value
}
} else {
n = new Node(value);
return n; //returns the new node after creating (adding) it
}
return n;
}
Why do I have to set n.right
and n.left
to the return value from addToTree()
? I don't understand why a void function wouldn't work here and why the new node has to be returned. Does this explain the 'Pass by value' nature of Java? When addToTree(n.left, value)
is called, is it not passing the reference to n.left
?