最初に配列を(順番に)構築し、次に配列からツリー全体を再構築することで、BSTのバランスをとろうとしています。
私は持っています:
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);
助けていただければ幸いです。