【问题标题】:java.lang.NullPointerException while creating BinaryTree from preorder and inorder [duplicate]java.lang.NullPointerException 从前序和中序创建 BinaryTree [重复]
【发布时间】: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


【解决方案1】:

preptr 在您突出显示的行上为空。它是空的,因为您通过执行preptr.next 递归调用construct,但并不总是有preptr.next,因此您需要在调用construct 之前检查preptr.next 是否存在,或者您需要签入construct如果 arg 为 null,则为您的情况做一些有意义的事情

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    相关资源
    最近更新 更多