How to return a list of values through recursion i

2019-07-28 16:40发布

Returning a single value through recursion works just fine. But what if I want to return a list of values that recursion goes through each call. Here's my code.

public void inOrder(Node focusNode) {

  /* ArrayList<Integer> tempList = new ArrayList<Integer>(); */

  if ( focusNode != null) {

    inOrder(focusNode.getLeftNode());
    System.out.println(focusNode);
    /*  tempList.add(focusNode.getElement()); */
    inOrder(focusNode.getRightNode());

  }

/*  int[] elems = new int[tempList.toArray().length];
  int i = 0;
  for ( Object o : tempList.toArray()) 
    elems[i++] = Integer.parseInt(o.toString()); */

  //return tempList;
}

printing values while traversing through gives the expected output. But storing those values is not working. It only returns with a single value in a list. Can someone help me with this?

1条回答
地球回转人心会变
2楼-- · 2019-07-28 17:14

Why don't you just pass in a reference to an array list along with your starting node? After your inOrder method runs, you'll have an ordered series of values that you can use as you please.

// method signature changed
public void inOrder(Node focusNode, ArrayList vals) {

    /* ArrayList<Integer> tempList = new ArrayList<Integer>(); */

    if ( focusNode != null) {
        // args changed here
        inOrder(focusNode.getLeftNode(), vals);
        // adding node to array list rather than dumping to console
        vals.add(focusNode);
    /*  tempList.add(focusNode.getElement()); */
        inOrder(focusNode.getRightNode());
}
查看更多
登录 后发表回答