Edit: If your data structure has parent pointers, use them instead of looking for your descendants in the tree. If not, consider adding them. See Response from whiskeysierra for a solution with parent pointers. Only if you cannot add them, consider this answer.
In the current answer, everyone has two loops through children (one in children.contains() , one later).
This option may be a little more efficient (but it does not change the O-class), and a little shorter. (If children are a set with quick check-content (like a HashSet), and often the hierarchy is not so deep (so you don't need to recursively at all), other answers are better.)
public boolean isDescendant(Member x) { for(Member child : children) { if(child.equals(x) || child.isDescendant(x)) return true; } return false; }
If a node is considered a descendant of itself, you can write it as follows:
public boolean isDescendant(Member x) { if(equals(x)) return true; for(Member child : children) { if(child.isDescendant(x)) return true; } return false; }
Paลญlo Ebermann
source share