如何在Java中使用递归保留信息
基本上,每次递归时,我都会重置变量“path”,但我需要保留这些信息。此外,我不能将其作为参数传递。有办法做到这一点吗 以下是我现在掌握的代码:如何在Java中使用递归保留信息,java,recursion,Java,Recursion,基本上,每次递归时,我都会重置变量“path”,但我需要保留这些信息。此外,我不能将其作为参数传递。有办法做到这一点吗 以下是我现在掌握的代码: public List<Person> getDiseaseRouteTo(Person c){ List<Person> path = new LinkedList<Person>(); if (this.root == c) { path.add(c); } e
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;
}
公共列表getDiseaseRouteTo(c人){
列表路径=新建LinkedList();
if(this.root==c){
路径。添加(c);
}else if(this.root!=c){
path.add(this.root);
for(DiseaseTree子项:this.getChildren()){
if(子项包含(c)){
add(child.getRoot());
返回child.getDiseaseRouteTo(c);
}
}
}
返回路径;
}
此外,我不能将其作为参数传递
您始终可以创建一个可以传递它的私有助手方法:
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) {
// ...
}
公共列表getDiseaseRouteTo(c人){
列表路径=新建LinkedList();
返回getDiseaseRouteTo(c,路径);
}
私有列表getDiseaseRouteTo(个人c,列表路径){
// ...
}
每次调用该方法时,您都在创建一个新的LinkedList实例
您可以像janos建议的那样,在getDiseaseRouteTo
方法范围之外的其他地方创建path
变量。我认为这很好。你的代码有问题吗?