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;
}
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) {
// ...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With