I am trying to write a function in java to convert a binary tree to DLL. The function executes without error but the DLL is not being made. Following is the function. root is pointer to the root of the tree and head points to the starting node of the DLL.
public void dll(Node x)
{
if(x==null)
{
return;
}
else
{
if(x==root)
{
Node temp=root;
while(temp.left!=null)
{
temp=temp.left;
}
head=temp;
}
if(x.left!=null)
{
System.out.println(x.data);
Node lchild=x.left;
Node rightmost=lchild;
while(rightmost.right!=null)
{
rightmost=rightmost.right;
}
x.left=rightmost;
rightmost.right=x;
dll(lchild);
}
if(x.right!=null)
{
System.out.println(x.data);
Node rchild=x.right;
Node leftmost=rchild;
while(leftmost.left!=null)
{
leftmost=leftmost.left;
}
x.right=leftmost;
leftmost.left=x;
dll(rchild);
}
}
}
}
The logic is as follows: Find the rightmost in left subtree and make is previous node of root and find leftmost in right sub tree and make it next of the root. Recursive apply for subtrees.
When I try to print head.right, it gives me Null pointer exception.
Exception in thread "main" java.lang.NullPointerException
at BTtoDll.main(BTtoDll.java:153)
Line 153 is -
System.out.println(t.head.right.data);