Search code examples
javaarraysrecursionbinary-treetraversal

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

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?


Solution

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