我正在尝试在 java 中实现三叉树。但我的代码中出现空指针异常
Exception in thread "main" java.lang.NullPointerException
at TreeStructure.printNode(TreeStructure.java:67)
at TreeStructure.printNode(TreeStructure.java:64)
at TreeStructure.runTree(TreeStructure.java:95)
at TreeStructure.main(TreeStructure.java:109)
我的主要树代码是
public class TreeStructure
{
public Node root;
/**
* @param args
*/
public void insert(Node node, String value)
{
if(value.compareTo(node.value)<0)
{
if (node.left!=null)
{
insert(node.left,value);
}
else
{
System.out.println("Inserted"+value+"to left of"+ node.value);
node.left=new Node(value);
node.left.parent=node;
}
}
else if(value.compareTo(node.value)>0)
{
if(node.right!=null)
{
insert(node.left,value);
}
else
{
System.out.println("Inserted"+value+"to right of "+node.value);
node.right=new Node(value);
node.right.parent=node;
}
}
else if(value==node.value)
{
if(node.middle==null)
{
insert(node.middle,value);
}
else
{
System.out.println("Inserted"+value+"to middle of"+node.value);
node.middle=new Node(value);
node.middle.parent=node;
}
}
}
public void printNode(Node node)
{
if(node!=null)
{
printNode(node.left);
System.out.println("Tree traversal"+node.value);
}
if(node.parent!=null)
{
System.out.println("parent is"+node.parent.value);
}
else
{
System.out.println("");
printNode(node.middle);
printNode(node.right);
}
///need to add some code here
}
public void TestInsert(Node start)
{
System.out.println("Testcase Insert");
insert (root,"Astana");
insert(root,"Asgrad");
insert(root,"Lychs");
insert (root,"Brac");
insert(root,"London");
insert(root,"Arad");
insert(root,"Kathmundu");
printNode(start);
}
public void runTree()
{
root=new Node("Asgrad");
System.out.println("Tree build with"+ root.value);
printNode(root);
TestInsert(root);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
TreeStructure tree=new TreeStructure();
tree.runTree();
}
}
我的节点类是
public class Node
{
Node parent;
Node left;
Node right;
Node middle;
String value;
public Node(String value)
{
this.parent=null;
this.left=null;
this.right=null;
this.middle=null;
this.value=value;
}
}
我正在尝试解决这个问题,但我无法找出错误。如果有人帮我找到问题,那就太好了......提前致谢