void (DirectNode root, List<? super DirectNode> lst) { LinkedList<DirectNode> stackNode = new LinkedList<>(); LinkedList<Integer> stackIndex = new LinkedList<>(); HashSet<DirectNode> setVisited = new HashSet<>(); stackNode.add(root); stackIndex.add(0); while (!stackNode.isEmpty()) { DirectNode node = stackNode.getLast(); int index = stackIndex.removeLast(); setVisited.add(node); for (; index < node.successors.size(); index++) { DirectNode succ = node.successors.get(index); if (!setVisited.contains(succ)) { stackIndex.add(index + 1); stackNode.add(succ); stackIndex.add(0); break; } } if (index == node.successors.size()) { lst.add(0, node); stackNode.removeLast(); } } }