Hi, im trying to implement code for a binary search tree. This method should take all the elements in the tree and add them to a vector sorted with lowest first, the elements in the tree are inorder.

It gives me java.lang.ArrayIndexOutOfBoundsException at a[temp]=n.element;

/* * 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> n, E[] a, int index) { return addArray(n, a, index); } private int addArray(BinaryNode<E> n, E[] a, int index){ if(n != null && index>=0 ){ int temp = index; temp = addArray(n.left, a, temp); a[temp]=n.element; temp++; temp = addArray(n.right, a, temp); return temp; } else { return index; }}

Its a part of another public method that rebuilds the tree. The purpose of the rebuild method is to make the tree balanced.

/** * Builds a complete tree from the elements in the tree. */ public void rebuild() { E[] a = (E[]) new Comparable[size]; int first= 0; int last = toArray(root, a, first); root= buildTree(a, first, last-1 ); }

And this is my main program where i test to add elements (ints) to the tree and then rebuild it:

public static void main(String[] args){ BSTVisualizer bstv = new BSTVisualizer("Fint träd", 500, 500); BinarySearchTree<Integer> tree = new BinarySearchTree<Integer>(); // for(int i=3; i<10; i++){ // tree.add(i); // tree.add(i); // } tree.add(4); tree.add(5); tree.add(3); tree.add(1); tree.add(1); tree.add(2); tree.add(8); tree.add(7); tree.rebuild(); bstv.drawTree(tree); System.out.println(tree.height()); System.out.println("//"); System.out.println(tree.size()); System.out.println("//"); tree.printTree(); } }

I appreciate any help i receive! Ty!