我试图通过首先构建一个数组(有序)然后从我的数组重建整个树来平衡 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);
任何帮助表示赞赏。