How to return a list of values through recursion in java?

血红的双手。 提交于 2019-12-11 05:21:23

问题


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:


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


来源:https://stackoverflow.com/questions/38531849/how-to-return-a-list-of-values-through-recursion-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!