【问题标题】:Binary Search Tree to inOrder Array二叉搜索树到 inOrder 数组
【发布时间】:2013-04-09 15:15:25
【问题描述】:

很简单的问题:

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

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

【问题讨论】:

    标签: java arrays binary-search-tree


    【解决方案1】:

    有序意味着您首先必须遍历树的左侧,所以:

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

    【讨论】:

      【解决方案2】:

      谢谢,效果很好。 Java不允许我创建一个泛型数组,所以使用你的算法我让它与一个ArrayList一起工作(就像你建议的那样)这是方法(使用上面的构造函数),以防其他人问同样的问题。 (ref是我对当前树节点的引用)

      public ArrayList<E> toArray() {
          ArrayList<E> result = new ArrayList<E>();
          toArrayHelp(root, result);
          return result;
      }
      
      private void toArrayHelp(TreeNode ref, ArrayList<E> result) {
          if (ref == null) {
              return;
          }
          toArrayHelp(ref.left, result); 
          result.add(ref.data); 
          toArrayHelp(ref.right, result); 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        相关资源
        最近更新 更多