Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retain information using a recursion in Java

Tags:

java

recursion

Basically, every time I recurse, I reset the variable "path," but I need to keep that information. Also, I cannot pass it as a parameter. Is there a way to do this?

Here is the code I have now:

public List<Person> getDiseaseRouteTo(Person c){

    List<Person> path = new LinkedList<Person>();

    if (this.root == c) {
        path.add(c);
        } else if (this.root != c) {
            path.add(this.root);
            for (DiseaseTree child: this.getChildren()) {
                if (child.contains(c)) {
                    path.add(child.getRoot());
                    return child.getDiseaseRouteTo(c);
                }
            }
        }
        return path;
    }
like image 645
M.L Avatar asked Dec 07 '25 01:12

M.L


2 Answers

Also, I cannot pass it as a parameter.

You can always create a private helper method where you can pass it:

public List<Person> getDiseaseRouteTo(Person c) {
    List<Person> path = new LinkedList<Person>();
    return getDiseaseRouteTo(c, path);
}

private List<Person> getDiseaseRouteTo(Person c, List<Person> path) {
    // ...
}
like image 134
janos Avatar answered Dec 08 '25 13:12

janos


You are creating a new instance of LinkedList every time you invoke the method.

You can create the path variable elsewhere, outside the scope of the getDiseaseRouteTo method, like janos suggested.

like image 42
Kevin Avatar answered Dec 08 '25 15:12

Kevin