title: Converting Binary tree to Doubly linked list
body: <p>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.</p>
  
  <pre><code>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);
              }
  
  
  
  
          }
  
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p><img src="https://i.stack.imgur.com/8KvYY.jpg" alt="enter image description here"></p>
  
  <p>When I try to print head.right, it gives me Null pointer exception.</p>
  
  <pre><code>Exception in thread "main" java.lang.NullPointerException
          at BTtoDll.main(BTtoDll.java:153)
  </code></pre>
  
  <p>Line 153 is  -</p>
  
  <pre><code> System.out.println(t.head.right.data);
  </code></pre>