如何使用Java中的递归来保留信息

M.L*_*M.L 3 java recursion

基本上,每次我递归时,我都会重置变量"path",但我需要保留这些信息.另外,我不能将它作为参数传递.有没有办法做到这一点?

这是我现在的代码:

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;
    }
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 6

另外,我不能将它作为参数传递.

您始终可以创建一个私有帮助程序方法,您可以在其中传递它:

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) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)