【问题标题】:Binary search tree into array二叉搜索树成数组
【发布时间】:2014-03-12 23:36:46
【问题描述】:

我坚持将返回的 BS 树放入一个数组中。我想问题是我没有绕过计数器来确定下一个空闲索引在哪里(我打算将计数器作为数组的第一个元素以使其更容易)。有什么建议吗?

  public int[] returnInOrderTraversal(){
       int[] arr = new int[getSize()+1];
  if (rootNode != null)
  {
      rootNode.returninOrderTraversal(arr);
  }
return arr;
   }


public void returninOrderTraversal(int[] arr){
  if(this.getLeftChild() != null)
  {
      this.getLeftChild().returninOrderTraversal(arr);

  }
  arr[arr[0]++] = this.getValue();
  if (this.getRightChild() != null)
  {
      this.getRightChild().returninOrderTraversal(arr);
  }  
}

【问题讨论】:

    标签: java arrays tree binary-tree binary-search-tree


    【解决方案1】:

    你所要做的就是换行:

    arr[arr[0]++] = this.getValue();
    

    到:

    arr[++arr[0]] = this.getValue();
    

    见How do the post increment (i++) and pre increment (++i) operators work in Java?

    你也可以考虑使用ArrayList代替数组,这样可以获得同样的性能,而且在这种情况下根本不需要关心索引。只需使用add 方法即可。

    【讨论】:

    • 不,仍然是“java.lang.ArrayIndexOutOfBoundsException”
    • 您能添加更多代码吗? getSize() 方法长什么样子?
    • 你的 getSize() 方法有问题,添加 5 个节点后,getSize() 方法返回 2。调用 getSize() 时你只看左子或右子,你必须查看它们并添加这两个尺寸...
    • 谢谢,我已经改成正确的了,添加了打印方法 public void printArray() { int[] arr = new int[getSize()+1]; returnInOrderTraversal(); System.out.println("数组:" + arr); } 现在输出是 [I@4187a8e0 而不是 1 2 4 5 9 12。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2016-06-05
    • 2013-04-09
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    相关资源
    最近更新 更多