我正在尝试完成这个程序,但我一直得到这个空指针异常错误,我不确定如何解决这个问题。任何帮助将不胜感激。
这是我的错误:
Exception in thread "main" java.lang.NullPointerException
at BinarySearchTree.insert(BinarySearchTree.java:45)
at BinarySearchTree.insert(BinarySearchTree.java:37)
at TreeDemo.main(TreeDemo.java:22)
这是第45行:int R = root.getString().compareTo(n.getString());
line 37: this.insert(root,n);
这是我的二叉搜索树类:
import java.util.Stack;
import java.util.Stack;
public class BinarySearchTree {
private Node root, n;
private int size;
public BinarySearchTree () {
root = null;
size = 0;
}
public void add (Node b){
if(root == null){ //tree is empty
root = b;
}else{
root.add (b);
}
}
public void search(String word){
Node n=new Node(word);
this.search(root,n);
}
public void insert(String word){
Node n = new Node(word);
this.insert(root,n);
}
public void insert(Node start,Node n){
int R = root.getString().compareTo(n.getString());
if(R==-1)
{//before
if(start.left==null)
{
start.left=n;
}
else
{
insert(start.left,n);
}
}
else if(R==1)
{//after
if(start.right==null)start.right=n;
else insert(start.right,n);
}
else
{
start.nodeFreq++;
//System.out.print(nodeFreq);
}
}
public Node search(Node start, Node n){
int R = root.getString().compareTo(n.getString());
if(R==-1)
{//before
if(start.left==null)
{
return null;
}
else
{
insert(start.left,n);
}
}
else if(R==1)
{//after
if(start.right==null)return null;
else insert(start.right,n);
System.out.println("word found");
}
else
{
return start;
}
return start;
}
public void printPreOrder(){
this.printPreOrder(root);
}
public void PreOrder(Node n){
this.printPreOrder();
}
public void printInOrder(){
this.printInOrder(root);
}
public void InOrder(Node n){
this.printInOrder();
}
public void printPostOrder(){
this.printPostOrder(root);
}
public void PostOrder(Node n){
this.printPostOrder();
}
public void printPreOrder(Node root){
if(root!=null){
System.out.print(root+ " ");
printPreOrder(root.leftNode());
printPreOrder(root.rightNode());
}
}
public static void printInOrder(Node root){
if(root != null){
printInOrder(root.left);
System.out.print(root + " ");
printInOrder(root.right);
}
}
public static void printPostOrder(Node root){
if(root!=null){
printPostOrder(root.leftNode());
printPostOrder(root.rightNode());
System.out.print(root + " ");
}
}
}
答案 0 :(得分:0)
如果您将节点插入空树,node
为null
。此外,我认为您的代码应该是int R = start.getString().compareTo(n.getString());
,您应该先判断start != null
。