【问题标题】:Java StackOverflowError while recursively building an array from a binary search treeJava StackOverflowError,同时从二叉搜索树递归构建数组
【发布时间】:2010-10-31 20:59:21
【问题描述】:

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

任何帮助表示赞赏。

【问题讨论】:

    标签: java binary-tree rebuild stack-overflow


    【解决方案1】:
    index = toArray(node, a, index);
    

    您想写node.leftnode.right

    【讨论】:

    • Off cause =) 抱歉浪费您的时间。谢谢!
    • 我以为我做到了?我点击了复选标记,它说再等七分钟,所以我做了,再次点击它,它变成了绿色。我错过了什么吗?
    • 为什么人们不赞成这个问题本身?这让我疯狂。我从来没有在不赞成问题本身的情况下赞成答案。如果答案值得一票,那么问题肯定也是。
    【解决方案2】:

    这里是:

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

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

    【讨论】:

      猜你喜欢
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 2014-01-02
      • 2021-09-01
      • 1970-01-01
      相关资源
      最近更新 更多