我正在尝试在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();
}
}
我的Node类是
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;
}
}
我试图解决这个问题,但我无法弄清楚错误。如果有人帮我找到问题会很棒...... 提前致谢
答案 0 :(得分:0)
你有一些问题,但只关注你当前的异常。 。 。你需要改变这个:
if(node.parent!=null)
到此:
if(node != null && node.parent != null)
您需要学习如何读取堆栈跟踪。 : - )
答案 1 :(得分:0)
看这里:
if(node.parent !=null) // node might be null, exception might be thrown
{
[..]
}
else // node might be null
{
System.out.println("");
// here node might be null and the exception can be thrown
printNode(node.middle);
printNode(node.right);
}