tags:

views:

144

answers:

1

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??

+8  A: 

Your problem is that ro variable inside the insert method is just a copy of the reference to bst.ro. Meaning that if you reset the ro variable inside the method, just the copy of the reference will point the new ro, 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.

Ciwee