gpt4 book ai didi

java - 如何使用递归函数返回 ArrayList

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:55:08 26 4
gpt4 key购买 nike

我是 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[] 来保存它们。一种更有效的方法是提供一个列表来填充。

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

这会创建更少的对象(如果列表有足够大的容量,可能没有)

关于java - 如何使用递归函数返回 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27886116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com