2

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

任何帮助表示赞赏。

4

2 回答 2

5
index = toArray(node, a, index);

你想写node.left还是node.right

于 2010-10-31T12:59:21.467 回答
1

这里是:

if (node.left != null) {
    index = toArray(node, a, index);
}

你可能想用index(例如增量)或节点(比如,node = node.left)做一些事情(我没有研究你的算法,只是一般性建议)。

于 2010-10-31T12:58:46.323 回答