从二叉搜索树递归构建数组时出现 Java StackOverflowError

标签 java binary-tree rebuild stack-overflow

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

关于从二叉搜索树递归构建数组时出现 Java StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4063160/

相关文章:

c++ - 重建一个通过引用发送的变量

c - 重建/更新内核模块

java - Java HashMap 调整大小的时间复杂度

java - 在 Java 中使用分隔符逗号在嵌套大括号中拆分字符串

javascript - 递归遍历二叉树Javascript的所有嵌套子节点

c - 在 C 中用字符串插入二叉树

Flutter聊天列表更新重建效率

java - JAR 文件在文件系统的不同位置表现不同

Java 分析、性能调优和内存分析练习

c - 二叉树,打印出我在哪一层