Search code examples
javarecursionnullpointerexceptionbinary-treerecursive-datastructures

java.lang.NullPointerException while creating BinaryTree from preorder and inorder


I don't know why this code is throwing a runtime error

    static class TreeNode<E>
{
    E data;
    TreeNode<E> right, left;
    
    TreeNode(E data)
    {
        this.data=data;
        right=left=null;
    }
}

inpte: To store inorder in a manually implemented LinkedList. preptr: To store preorder in a manually implemented LinkedList. num: To store the total number of nodes in the tree.

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;
}

error thrown:

 Exception in thread "main" java.lang.NullPointerException
    at practiceCodes.PreAndIn.construct(PreAndIn.java:32)
    at practiceCodes.PreAndIn.main(PreAndIn.java:104)

Solution

  • preptr on the line you highlighted is null. And it is null because you call construct recursively by doing preptr.next but there isn't always a preptr.next so you need to check whether preptr.next exists before calling construct or you need to check in construct if the arg is null, then do something meaningful for your case