Я пытаюсь сбалансировать BST, сначала создав массив (inorder), а затем перестроил все дерево из моего массива.
У меня есть:
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;
}
и
bst.toArray(b);
Я надеялся, что это создаст порядок массивов. Но я получаю StackOverflowError. Как я понимаю, это возможно из-за бесконечной рекурсии, но я действительно не вижу этого.
Ошибка в этой строке:
index = toArray(node, a, index);
Любая помощь приветствуется.