簡體   English   中英

如何使用遞歸函數返回ArrayList

[英]How to return an ArrayList with an recursive function

我是java新手,我一直在努力...我必須做一些功課,我從中解決了很多,但在某些方面,我不知道該怎么做。 我的問題:我必須為二叉樹構建一些函數(例如添加節點,計數節點,刪除節點等)。 他們中的大多數我都能找到自己的算法。 現在我正在努力使用遞歸方法。 我在其中添加了注釋來解釋我的問題是什么:

    public List<E> getPreOrderList() {
    //TO DO:
    //this function should return  a list of the nodes in pre-order (value, left, right).
    //It must be implemented recursively!!!

    //THE PROBLEM:
    //If i create an ArrayList<E> inside the function, the 
    //recursion will generate each time a new ArrayList.
    //At the end i get as result an ArrayList with only one node.
    ArrayList<E> list = new ArrayList<E>();

    if (this.value == null) {
        return null;
    }
    //If I just print out the nodes, the pre-order algorithm is OK,
    //but i need to return all nodes into an ArrayList.
    System.out.print(value + ", ");
    list.add(value);
    if (left != null) {
        left.getPreOrderList();
    }
    if (right != null) {
        right.getPreOrderList();
    }
    return list;
}

有兩種方法可以做到這一點,簡單但效率低下。

public List<E> getAll() {
     List<E> list = new ArrayList<>();
     if (value != null) list.add(value);
     if (left != null) list.addAll(left.getAll());
     if (right != null) list.addAll(right.getAll());
     return list;
}

這會生成大量的列表和Object []來保存它們。 一種更有效的方法是提供一個List來填充。

public List<E> getAll(List<E> list) {
     if (value != null) list.add(value);
     if (left != null) left.getAll(list);
     if (right != null) right.getAll(list);
     return list;
}

這會創建更少的對象(如果列表具有足夠大的容量,則可能沒有)

您可以將列表傳遞給遞歸方法。 這樣您只需創建一次列表。

public List<E> getPreOrderList() {
    ArrayList<E> list = new ArrayList<E>();
    getPreOrderListRec(list);
    return list;
}

public void getPreOrderListRec(List<E> list) {
    // logic of recursive method, which add elements to the list
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM