Created
September 28, 2017 03:45
-
-
Save MatthewLQM/4ba6302a8019ddc2d5c38a1e80aaa8b0 to your computer and use it in GitHub Desktop.
非迭代版本的 DFS 的 Java 实现
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 使用栈存储遍历过的节点,依次 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