I have this code fragment
class bst {
public node root=null;
bst() {
root=null;
}
public void insert(int data) {
insert(this.root,data);
}
private void insert(node ro,int data) {
if (ro==null) {
print ("root is null");
ro=new node(data);
} else if (data>ro.data)
insert(ro.right,data);
else
insert(ro.left,data);
}
private void print (String str)
{
System.out.println(str);
}
}
When I call the insert function like insert(5); insert(8); it alwaty prints root is null.
whats the problem??
Your problem is that
rovariable inside theinsertmethod is just a copy of the reference tobst.ro. Meaning that if you reset therovariable inside the method, just the copy of the reference will point the newro, the originally passed object will remain the same.Your question is the top 1 of Parameter Passing FAQ. I myself already answered this question more than once. Check it out.