Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As others have mentioned, build a hashtable/map of objects to a list of their (direct) children.</p> <p>From there you can easily lookup a list of direct children of your "target object", and then for each object in the list, repeat the process.</p> <p>Here's how I did it in Java and using generics, with a queue instead of any recursion:</p> <pre><code>public static Set&lt;Node&gt; findDescendants(List&lt;Node&gt; allNodes, Node thisNode) { // keep a map of Nodes to a List of that Node's direct children Map&lt;Node, List&lt;Node&gt;&gt; map = new HashMap&lt;Node, List&lt;Node&gt;&gt;(); // populate the map - this is O(n) since we examine each and every node // in the list for (Node n : allNodes) { Node parent = n.getParent(); if (parent != null) { List&lt;Node&gt; children = map.get(parent); if (children == null) { // instantiate list children = new ArrayList&lt;Node&gt;(); map.put(parent, children); } children.add(n); } } // now, create a collection of thisNode's children (of all levels) Set&lt;Node&gt; allChildren = new HashSet&lt;Node&gt;(); // keep a "queue" of nodes to look at List&lt;Node&gt; nodesToExamine = new ArrayList&lt;Node&gt;(); nodesToExamine.add(thisNode); while (nodesToExamine.isEmpty() == false) { // pop a node off the queue Node node = nodesToExamine.remove(0); List&lt;Node&gt; children = map.get(node); if (children != null) { for (Node c : children) { allChildren.add(c); nodesToExamine.add(c); } } } return allChildren; } </code></pre> <p>The expected execution time is something between O(n) and O(2n), if I remember how to calculate that right. You're guaranteed to look at every node in the list, plus a few more operations to find all of the descendants of your node - in the worst case (if you run the algorithm on the root node) you are looking at every node in the list twice.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload