Skip to content

Instantly share code, notes, and snippets.

@MatthewLQM
Created September 28, 2017 03:45
Show Gist options
  • Save MatthewLQM/4ba6302a8019ddc2d5c38a1e80aaa8b0 to your computer and use it in GitHub Desktop.
Save MatthewLQM/4ba6302a8019ddc2d5c38a1e80aaa8b0 to your computer and use it in GitHub Desktop.
非迭代版本的 DFS 的 Java 实现
/**
* 使用栈存储遍历过的节点,依次 pop 出来进行处理。
 * 注意 reverse 操作,保证了遍历从左子节点到右子节点。
* @Author MatthewLQM
*/
private static void iterativeDFS(Node root) {
Deque<Node> stack = new ArrayDeque<Node>();
stack.push(root);
while (!stack.isEmpty()) {
Node node = stack.pop();
if (node instanceof TextNode) {
System.out.print(node);
       }
       List<Node> nodes = new ArrayList<Node>(node.childNodes());
Collections.reverse(nodes);
      nodes.foreach(child -> stack.push(child));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment