new node not assigning to a tree when we make it by passing into method but working when made directly, not passing into method.
I have made Node class and MYBinarySearchTree class. when i pass the root node and data in insertIt method then it is giving nullpointerexception in runtime.
class Node{
int data;
Node left, right;
Node(int d){
data = d;
left = right = null;
}
}
class MyBinarySearchTree{
Node root ;
MyBinarySearchTree(){
root = null;
}
void insert(int data){
//root = new Node(data);
insertIt(root,data);
}
static void insertIt(Node node, int data){
node = new Node(data);
}
}
class BinarySearchTree{
public static void main(String[] args) {
MyBinarySearchTree bst = new MyBinarySearchTree();
bst.insert(45);
System.out.println(bst.root.data);
}
}
this above code is not working.
void insert(int data){
root = new Node(data);
//insertIt(root,data);
}
static void insertIt(Node node, int data){
node = new Node(data);
}
this above code is working
i don't understand what is difference between the two, because in java objects are pass by reference, so it should give same result.