代码之家  ›  专栏  ›  技术社区  ›  evading

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

  •  2
  • evading  · 技术社区  · 14 年前

    我有:

     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);
    

    我希望这能建立一个有序的数组。但我有StackOverflower错误。据我所知,这可能是由于无限递归,但我真的看不到它。

    错误发生在这一行:

    index = toArray(node, a, index);
    

    2 回复  |  直到 14 年前
        1
  •  5
  •   starblue    14 年前
    index = toArray(node, a, index);
    

    你想写 node.left node.right

        2
  •  1
  •   Roman    14 年前

    这里是:

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

    你可能想做点什么 index node = node.left )(我没有调查你的算法,只是一般性的建议)。