As already mentioned, build a hash table / map of objects into a list of your (direct) child elements.
From there, you can easily find the list of direct children of your “target”, and then repeat the process for each object in the list.
Here's how I did it in Java and used generics, with a queue instead of any recursion:
public static Set<Node> findDescendants(List<Node> allNodes, Node thisNode) {
Map<Node, List<Node>> map = new HashMap<Node, List<Node>>();
for (Node n : allNodes) {
Node parent = n.getParent();
if (parent != null) {
List<Node> children = map.get(parent);
if (children == null) {
children = new ArrayList<Node>();
map.put(parent, children);
}
children.add(n);
}
}
Set<Node> allChildren = new HashSet<Node>();
List<Node> nodesToExamine = new ArrayList<Node>();
nodesToExamine.add(thisNode);
while (nodesToExamine.isEmpty() == false) {
Node node = nodesToExamine.remove(0);
List<Node> children = map.get(node);
if (children != null) {
for (Node c : children) {
allChildren.add(c);
nodesToExamine.add(c);
}
}
}
return allChildren;
}
- - O (n) O (2n), , . node , , node - ( node), node .