Your structure is similar to ona, which I have in my application. I solve this problem by creating a common walker that descends three from the root and uses the visitor pattern to provide me with the result of the walk.
If you convert it to your problem, it will look like this:
public class SimpleWalker<T>{ private Visitor<T> visitor; public SimpleWalker(Visitor<T> visitor) { this.visitor= visitor; } public void walk(Member node) { if (visitor.visit(node)) { for (Member child : node.children) { walk(child); } } visitor.leave(node); } public T getResult() { return visitor.getResult(); } }
and then the visitor interface
public interface Visitor<T> { boolean visit(Member node); void leave(Member node); T getResult(); }
and the implementation will look like this:
public class Pathfinder implements Visitor<List<Member>> { final private String firstname, secondname;//passed by constructor boolean found = false; List<Member> path = new ArrayList<>(); public boolean visit(Member node) { if (node.firstname.equals(firstname) && node.secondname.equals(secondname)) { found = true; return false; } return true; } public void leave(Member node) { if (found){ path.add(0, node); } } public List<Member> getResult() { return path; } }
The advantage of this solution is that you want to do something in the tree, for example, we find an element, count the number of descendants of someone, you can use a walker, all you have to do is create a new visitor.
source share