0

I have some code. In main function i push six element in BST. when i look to debugger, i see that variable size = 5, but variable root = null. Why variable root not change.

package Search;

public class BST<Key extends Comparable<Key>, Val> {
private class Node{
    Key key;
    Val val;
    Node left;
    Node right;
    Node prev;
    Node(Key k, Val v){
        key = k;
        val = v;
    }
}
public void push(Key k, Val v){
    push(root,k,v);
}
private void push(Node x, Key k, Val v){
    if(x == null){
        x = new Node(k,v);
        size++;
        return;
    }
    int cmp = x.key.compareTo(k);
    if(cmp > 0)
        push(x.left,k,v);
    else if(cmp < 0)
        push(x.right,k,v);
    else
        x.val = v;

}
Node root = null;
int size = 0;
public static void main(String args[]){
    BST<String,Integer> bst = new BST<String, Integer>();
    bst.push("c",1);
    bst.push("b",2);
    bst.push("d",3);
    bst.push("a",4);
    bst.push("e",5);
    bst.push("c",6);
}

}

BenMorel
  • 34,448
  • 50
  • 182
  • 322
k_zaur_k
  • 400
  • 1
  • 6
  • 16

2 Answers2

5

In your if block, the assignment:

x = new Node(k,v);

doesn't make your root reference point to the new Node object. It's just the local x reference of that method which is assigned to new Node(). It won't affect root, which will be null only. This is because, Java passes the references by value. Once you change the reference value of x by assigning it to a new object, it will not be the same as root anymore.

Just remove that if block from the 2nd push() method. You should rather do that task in the first push() method only, where you initialize the root itself before passing it to the 2nd push() method:

public void push(Key k, Val v){
    if (root == null) {
        root = new Node(k, v);
        size++;
        return;
    }
    push(root,k,v);
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

Because you are passing root by value in push(Key k, Val v). So the assignment to x doesnt assign the field root.

nitegazer2003
  • 1,193
  • 5
  • 10