我试图通过首先构建一个数组(中序)然后从我的数组重建整个树来平衡 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);
感谢任何帮助。
最佳答案
index = toArray(node, a, index);
您想编写node.left
或node.right
吗?
关于从二叉搜索树递归构建数组时出现 Java StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4063160/