Say I have an object of type T with a field with an ArrayList that holds objects of type T that I will call list. I also have another object of type T that I will call goal. I am trying to find goal. To do this, I want to first iterate through the list to see if goal is there. If it is, I want to return the original object. If it is not, then I want to go object by object through list and check each of these lists for goal (returning the object if found). I want to continue this search recursively until a match is found.
I cannot figure out how to accomplish this. The two options I could think of were while loops and recursion. However, I have to oscillate between levels as I check the various lists and I cannot figure out how to do that.
Another thought I had was that what I want to do is the same thing as a level-order transversal of a tree. However, I have only learned about binary trees so far and I don't know how or if I could convert it to a tree much less if it's possible to do a level order traversal without traversing the whole tree.
Below, see code that I have written so far. This will only check to see if the first list matches and does not go deeper which is what I need.
/**
* Searches for the shortest path between start and end points in the graph.
* @param start
* @param end
* @return a list of data, starting with start and ending with end, that gives the path through
* the graph, or null if no such path is found.
*/
public List<T> shortestPath(T startLabel, T endLabel){
List<T> list = new ArrayList<>();
list.add(startLabel);
while(true){
List<T> successors = successorList(startLabel);
if (containsMatch(successors, endLabel)) {
findMatch(successors, endLabel);
}
}
}
Does this scenario make sense? If so, any thoughts? Is it even possible? (I tried searching but all of my queries turned up nothing useful)
Thanks in advance for any help. Cheers!