从二进制搜索树递归构建数组时的Java StackOverflowError

时间:2010-10-31 12:54:30

标签: java binary-tree rebuild stack-overflow

我试图通过首先构建一个数组(inorder)来平衡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);

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:5)

index = toArray(node, a, index);

您想写node.leftnode.right

答案 1 :(得分:1)

这里是:

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

您可能想要使用index(例如增量)或节点(例如,node = node.left)执行某些操作(我没有调查您的算法,只是一般建议)。

相关问题