二叉搜索樹的inOrder數組。

[英]Binary Search Tree to inOrder Array


Pretty easy question:

很簡單的問題:

Recursively how can I create an array of a binary search tree (in order) which uses this constructor:

遞歸地,如何創建使用此構造函數的二叉搜索樹數組(按順序):

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

2 个解决方案

#1


3  

In-Order means you first have to traverse the left part of the tree, so:

順序意味着首先要遍歷樹的左邊部分,因此:

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

The method itself could looks something like this:

方法本身可以是這樣的:

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
}

Somewhat like that. I am just not sure about the index and where it needs to be incremented. If you don't want to worry about the index or if you don't know how many nodes are in the tree, then use an ArrayList instead and transform it in the end to an array.

有點像。我只是不確定索引在什么地方需要增加。如果您不想擔心索引,或者不知道樹中有多少節點,那么可以使用ArrayList,最后將其轉換為數組。

Normally a cleaner call method is build around the recursive method like this:

通常,圍繞這樣的遞歸方法構建一個更干凈的調用方法:

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

#2


1  

Thanks, that worked great. Java wouldn't allow me to make an array of generics so using your algorithm I made it work with an ArrayList (like you suggested) Here's the method (using the above constructor) just incase someone else asks the same question. (Ref is my reference to the current tree node)

謝謝,偉大的工作。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); 
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/04/17/72f7ee762682c97f9fe69c52b66256dc.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com