I asked a similar question last time around concerning the second algorithm below and was referred to a Is Java “pass-by-reference” or “pass-by-value”? thread.
I get that when you pass a variable into a method, Java creates a shadow copy of it so you can't modify the original variable, but this is exactly what is confusing me.
Below are two somewhat similar algorithms to which I initially pass in a root Node-- the first one works but the second one doesn't.
First
public void insert(int element) {
Node temp = new Node(element);
if(root == null) {
root = temp;
root.parent = null;
size++;
} else {
insert(root, temp);
size++;
}
}
private void insert(Node current, Node temp) {
if(temp.element < current.element) {
if(current.leftChild == null) {
current.leftChild = temp;
} else {
insert(current.leftChild, temp);
}
}
else if(temp.element >= current.element) {
if(current.rightChild == null) {
current.rightChild = temp;
} else {
insert(current.rightChild, temp);
}
}
}
Ouput:
Second (doesn't work)
public void insert(int data) {
Node temp = new Node(data);
if(root == null) {
root = temp;
size++;
} else {
insert(root, temp);
size++;
}
}
private void insert(Node current, Node temp) {
if(current == null)
current = temp;
else if(temp.element < current.element)
insert(current.leftChild, temp);
else if(temp.element >= current.element)
insert(current.rightChild, temp);
}
Output:
I wrote the first one myself and got the second one from Wikipedia. Why does the first one work but not the second one?