2

I'm trying to balance a BST by first building an array (inorder) and then rebuild the entire tree from my array.

I have:

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

and:

bst.toArray(b);

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.

The error occurs on this line:

index = toArray(node, a, index);

Any help appreciated.

2 Answers 2

5
index = toArray(node, a, index);

You wanted to write node.left or node.right?

Sign up to request clarification or add additional context in comments.

3 Comments

Off cause =) sorry to waste your time. Thanks!
Thought i did? I clicked the check-mark and it said wait for seven more minutes so i did, clicked it again and it turned green. Have i missed something?
How comes people don't upvote the question itself? This drives me crazy on SO. I never, ever, upvote an answer without upvoting the question itself. If the answer is worthy a vote, the question definitely is too.
1

here it is:

if (node.left != null) {
    index = toArray(node, a, index);
}

you've probably wanted to do something with index (increment for example) or with the node (like, node = node.left) (I didn't investigate your algorithm, just general suggestions).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.