java - 二叉搜索树到 inOrder 数组

标签 java arrays binary-search-tree

很简单的问题:

如何递归地创建使用此构造函数的二叉搜索树数组(按顺序):

public class OrderedSet<E extends Comparable<E>> {
    private class TreeNode {
    private E data;
    private TreeNode left, right;

    public TreeNode(E el) {
        data = el;
        left = null;
        right = null;
    }
}

  private TreeNode root;
  public int size = 0;

  public OrderedSet() {
    root = null;
  }

最佳答案

按顺序意味着您首先必须遍历树的左侧部分,因此:

TreeNode tree  // this is your tree you want to traverse
E[] array = new E[tree.size];  // the arrays length must be equivalent to the number of Nodes in the tree
int index = 0; // when adding something to the array we need an index
inOrder(tree, array, index);  // thats the call for the method you'll create

该方法本身可能看起来像这样:

public void inOrder(TreeNode node, E[] array, int index){
    if(node == null){  // recursion anchor: when the node is null an empty leaf was reached (doesn't matter if it is left or right, just end the method call
       return;
    }
    inOrder(node.getLeft(), array, index);   // first do every left child tree
    array[index++]= node.getData();          // then write the data in the array
    inOrder(node.getRight(), array, index);  // do the same with the right child
}

有点像这样。我只是不确定索引以及它需要在哪里增加。如果您不想担心索引或者不知道树中有多少个节点,则可以使用 ArrayList 并将其最终转换为数组。

通常,更清晰的调用方法是围绕递归方法构建的,如下所示:

public E[] inOrderSort(TreeNode tree){
    E[] array = new E[tree.size];
    inOrder(tree, array, 0);
    return array;
}

关于java - 二叉搜索树到 inOrder 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16050219/

相关文章:

java - Android 对服务器进行 PATCH/PUT

java - 更改选定状态下的按钮形状?

Javascript:将数组数组拆分为多个数组

Java - 平衡 BinarySearchTree 的 JUnit 测试

java - 从一百万条记录中获取前 10 条和后 10 条

java - 有谁知道一个代表所有Java包的图表

java - Spring Boot 2.3 中不打印自定义异常的 Stacktrace

c - 如何确定 uint8_t 的数组长度?

c - Robotc(c修改)如何传递一个char数组变量

c++ - 使用 C++ 从排序的 std::list<float> 构建最小高度 BST