Binary Search Tree to Doubly Linked List
<p>I'm creating a Doubly Linked List from a Binary Search Tree using recursion and it works perfectly fine when the BST is already populated, i.e. >=2 nodes.
However, I tried running it for a BST that is dynamically getting populated and it gives me a StackOverFlowError as soon as I insert a child to the root node in the BST.
Here is the code (in Java) I've written</p>

<pre><code>public class BSTtoDLL {
/* Binary Search Tree to Doubly Linked List conversion*/

     // head --&gt; Pointer to head node of created doubly linked list
     static BTNode head;

     // Initialize previously visited node as NULL. This is
     // static so that the same value is accessible in all recursive
     // calls
     static BTNode prev = null;

    /* BSTtoDLL Construtor */
    public BSTtoDLL(){
        head = null;
        prev = null;
    }

     // A simple recursive function to convert a given Binary tree 
     // to Doubly Linked List
     // root --&gt; Root of Binary Tree
     void BinaryTree2DoubleLinkedList(BTNode root)
     {
         // Base case
         if (root == null)
             return;

         // Recursively convert left subtree
         if(root.left!=null)
            BinaryTree2DoubleLinkedList(root.left);

         // Now convert this node
         if (prev == null){
             head = root;
         }
         else
         {
             prev.right = root;
             root.left = prev;
         }
         prev = root;

         // Finally convert right subtree
         BinaryTree2DoubleLinkedList(root.right);
     }
</code></pre>

<p>And the the console response:</p>

<blockquote>
  <p>Binary Tree Test<br/>
  Converting to a DLL<br/>
  Data--34--Left is Null----Right
  is Null--- <br/>Binary Tree Test Converting to a DLL Exception in thread
  "main" java.lang.StackOverflowError<br/>  at
  com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)<br/>
    at
  com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)<br/>
    at
  com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)<br/>
    at
  com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)<br/>
    at
  com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)<br/></p>
</blockquote>