I think you can accomplish this with a boolean maxDepth = false
instance variable. On each iteration of your while loop, if maxDepth == true
then exit, else set maxDepth = true
. In dls
when you reach depth == 0
then set maxDepth = maxDepth && children.isEmpty()
, i.e. set maxDepth to false if the node has any children.
Also, change dls
to a void method. Replace return node.data
with results.add(node.data)
, where results
is an ArrayList
or HashSet
depending on whether you want to filter out duplicates.
If you always want to visit every node in the tree, then modify dls
as follows
public void dls(ArrayList<String> results, Node node, String goal)
{
if (node.data.contains(goal))
{
results.add(node.data);
}
for(Node child : node.children)
{
dls(child, goal, depth-1);
}
}