正如其他人所提到的,将对象的哈希表/映射构建到它们的(直接)子级列表。
从那里您可以轻松地查找“目标对象”的直接子项列表,然后对于列表中的每个对象,重复该过程。
以下是我在 Java 中使用泛型的方法,使用队列而不是任何递归:
public static Set<Node> findDescendants(List<Node> allNodes, Node thisNode) {
// keep a map of Nodes to a List of that Node's direct children
Map<Node, List<Node>> map = new HashMap<Node, List<Node>>();
// 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<Node> children = map.get(parent);
if (children == null) {
// instantiate list
children = new ArrayList<Node>();
map.put(parent, children);
}
children.add(n);
}
}
// now, create a collection of thisNode's children (of all levels)
Set<Node> allChildren = new HashSet<Node>();
// keep a "queue" of nodes to look at
List<Node> nodesToExamine = new ArrayList<Node>();
nodesToExamine.add(thisNode);
while (nodesToExamine.isEmpty() == false) {
// pop a node off the queue
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) 之间。您可以保证查看列表中的每个节点,再加上一些操作来查找节点的所有后代 - 在最坏的情况下(如果您在根节点上运行算法),您正在查看列表中的每个节点列表两次。