I made a code for Binary Search Tree. It has only Insert function. I am getting an error at insert()
function's while
condition.
Exception in thread "main" java.lang.NullPointerException
at tree.LinkNode.insert(BST.java)
at tree.BST.main(BST.java)
I have initialised the Dynamic variable stub
in the insert()
function using keyword new
.
Where did I go wrong?
The code has three class:
- BST (contain the main() class)
- LinkNode (contains LinkNode references and the insert() function)
- MyLinkNode (A class to initialise the root node)
Code:
public class BST {
public static void main(String[] args){
MyLinkNode start = new MyLinkNode(42);
LinkNode node = new LinkNode();
node.insert(start.root, 36);
}
}
class LinkNode{
LinkNode leftnode;
LinkNode rightnode;
LinkNode parentnode;
int value;
public LinkNode() {}
public String insert(LinkNode root, int val){
LinkNode stub = new LinkNode();
stub = root;
while(stub.leftnode == null || stub.rightnode == null){
if(stub.value < val){
stub = stub.leftnode ;
}
else if(stub.value > val){
stub = stub.rightnode;
}
else{
System.out.println("You Cannot insert a value that already exist in the tree.\nPlease insert a different value");
return "";
}
}
stub.value = val;
stub.leftnode = null;
stub.rightnode = null;
this.parentnode = stub;
return "Insertion Succesful";
}
}
class MyLinkNode{
LinkNode root;
public MyLinkNode(int val){
root = new LinkNode();
root.value = val;
root.parentnode = null;
root.leftnode = null;
root.rightnode = null;
}
}