1

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 Answer 1

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());
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you so much ! This is much better way than returning a list. :) One more question, does java also passes variables through reference?
@GauravP Please: if you are able to write such a question here ... then you are also able to put those same strings into a search engine. SO is not "programming school" where teachers explain things to you that are documented a zillion times. This is not meant to be rude; it is just what this site is about ... or not, in this case. In other words: you are expected to do "prior research"; and especially when you are a beginner: please understand that probably any "theoretical" question you can come up with ... was asked here before. And answered. Multiple. Times.
@GhostCat I completely get that. Apologies for that. It won't happen again.
@GauravP If my answer addressed your question, please click the checkmark on the left side to let future readers know what worked for you. Thanks.
@MarsAtomic worked? totally. It saved my 230 lines of code which was completely dependent on this sorted values. Thank You again (Even if stackoverflow suggest me to avoid)!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.