title: Java StackOverflowError while recursively building an array from a binary search tree
body: <p>I'm trying to balance a BST by first building an array (inorder) and then rebuild the entire tree from my array.</p>
  
  <p>I have:</p>
  
  <pre><code> public void toArray(E[] a) {
    toArray(root, a, 0);
   }
  
   /*
    * Adds all elements from the tree rooted at n in inorder to the array a
    * starting at a[index].
    * Returns the index of the last inserted element + 1 (the first empty
    * position in a).
    */
   private int toArray(BinaryNode&lt;E&gt; node, E[] a, int index) {
    if (node.left != null) {
     index = toArray(node, a, index);
    }
  
    a[index] = node.element;
    index++;
  
    if (node.right != null) {
     index = toArray(node, a, index);
    }
  
    return index;
   }
  </code></pre>
  
  <p>and:</p>
  
  <pre><code>bst.toArray(b);
  </code></pre>
  
  <p>I was hoping that this would build an array inorder. But i get StackOverflowError. As I understand that is probably due to infinite recursion but I really can't see it.</p>
  
  <p>The error occurs on this line:</p>
  
  <pre><code>index = toArray(node, a, index);
  </code></pre>
  
  <p>Any help appreciated.</p>