我为Binary Search Tree制作了一个代码。它只有Insert功能。我在insert()
函数while
条件下收到错误。
Exception in thread "main" java.lang.NullPointerException
at tree.LinkNode.insert(BST.java)
at tree.BST.main(BST.java)
我已使用关键字stub
初始化insert()
函数中的动态变量new
。
我哪里出错了?
代码有三个类:
代码:
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;
}
}