返回类型数组的递归树遍历方法 [英] Recursive Tree Traversal Method With Return Type Array
问题描述
是否有一种方法可以递归遍历树并返回范围为该递归方法的数组?
Is there a way to recursively traverse a tree and return an array that is scoped to that recursive method?
因此,我最近回答了有关此主题的其他人的问题.可以在以下位置找到该问题: SO问题.我的解决方案在递归范围之外使用数组,因此该方法无法(或至少可能不应)返回数组.但是,有没有一种方法可以编写遍历树的递归方法,使其返回数组?即使编写一个调用递归方法的初始方法也可以,但是我想不出一种好方法.
So I recently answered someone else's question on this topic. That question can be found here: SO Question. My solution uses an array outside of the scope of the recursion, and therefore the method cannot (or at least probably should not) return the array. However, is there a way to write a recursive method for traversing trees such that it returns an array? Even writing an initial method that calls the recursive one would be fine, but I can't think of a good way to do this.
这是我之前建议的代码:
Here's the code that I suggested before:
private List nodeValues = new ArrayList();
public void traversePreRecursive(BinarySearchTreeNode node)
{
if (node != null)
{
nodeValues.add(node.getValue());
traversePreRecursive(node.getLeft());
traversePreRecursive(node.getRight());
}
}
如您所见,ArrayList
不在递归的范围之内-因此,返回它没有多大意义.有更好的方法吗?
As you can see the ArrayList
is outside of the scope of the recursion - And therefore returning it doesn't make a lot of sense. Is there a better way to do this?
推荐答案
public static List traversePreRecursive(Node node) {
if (node == null) return new ArrayList();
List nodeValues = new ArrayList();
nodeValues.add(node.getValue());
nodeValues.addAll(traversePreRecursive(node.getLeft()));
nodeValues.addAll(traversePreRecursive(node.getRight()));
return nodeValues;
}
这篇关于返回类型数组的递归树遍历方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!