【发布时间】:2021-05-27 01:11:36
【问题描述】:
我不知道为什么这段代码会抛出运行时错误
static class TreeNode<E>
{
E data;
TreeNode<E> right, left;
TreeNode(E data)
{
this.data=data;
right=left=null;
}
}
inpte:将 inorder 存储在手动实现的 LinkedList 中。 preptr:将预购存储在手动实现的 LinkedList 中。 num:存储树中节点的总数。
TreeNode<E> construct(Node<E> inptr, Node<E> preptr, int num)
{
TreeNode<E> tmp;
Node<E> q;
int i,j;
if(num==0)
{
System.out.println("No node to create the tree");
return null;
}
tmp=new TreeNode<E>(preptr.data); //error line
if(num==1)
return tmp;
q=inptr;
for(i=0;q.data!=preptr.data;i++)
q=q.next;
tmp.left=construct(inptr, preptr.next, i);
for(j=1;j<=i+1;j++)
preptr=preptr.next;
tmp.right=construct( q.next, preptr, num-i-1);
return tmp;
}
抛出错误:
Exception in thread "main" java.lang.NullPointerException
at practiceCodes.PreAndIn.construct(PreAndIn.java:32)
at practiceCodes.PreAndIn.main(PreAndIn.java:104)
【问题讨论】:
标签: java recursion nullpointerexception binary-tree recursive-datastructures