我正在尝试以特定的后序遍历顺序收集所有节点。但是,当我唯一的函数是 getChildren() 而不是左孩子或右孩子时,我不太确定如何执行此操作。这是我目前在 Java 中进行的遍历。
Set<Node> postOrderedNodes = traverseSubAssembly(rootNode);
private static Set<Node> traverseSubAssembly(Node node) {
Set<Node> nodes = new HashSet<>();
nodes.add(node);
for (Node child : node.getChildren()) {
nodes.addAll(traverseSubAssembly(child));
}
return nodes;
}
Set<Node> postOrderedNodes = traverseSubAssembly(rootNode);
private static Set<Node> traverseSubAssembly(Node node) {
Set<Node> nodes = new HashSet<>();
for (Node child : node.getChildren()) {
nodes.addAll(traverseSubAssembly(child));
}
nodes.add(node);
// Add the node after its children have been processed not before.
return nodes;
}