Created
May 2, 2013 08:22
-
-
Save thorikawa/5500905 to your computer and use it in GitHub Desktop.
Implementation for non-recursive tree traversal
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
| package com.polysfactory.treetraversal; | |
| import java.util.Stack; | |
| /** | |
| * Implementation for tree traversal | |
| * | |
| * @author horikawa | |
| */ | |
| public class TreeTraversal { | |
| public static class Node { | |
| int id; | |
| Node left; | |
| Node right; | |
| public Node(int id, Node left, Node right) { | |
| this.id = id; | |
| this.left = left; | |
| this.right = right; | |
| } | |
| } | |
| private static final void visit(Node node) { | |
| System.out.println("Visit Node" + node.id); | |
| } | |
| public void preorder(Node root) { | |
| Stack<Node> stack = new Stack<Node>(); | |
| stack.add(root); | |
| while (!stack.empty()) { | |
| Node node = stack.pop(); | |
| visit(node); | |
| if (node.right != null) { | |
| stack.push(node.right); | |
| } | |
| if (node.left != null) { | |
| stack.push(node.left); | |
| } | |
| } | |
| } | |
| public void preorder2(Node root) { | |
| Stack<Node> stack = new Stack<Node>(); | |
| stack.add(root); | |
| Node node = null; | |
| while (!stack.empty()) { | |
| if (node == null) { | |
| node = stack.pop(); | |
| } | |
| visit(node); | |
| if (node.right != null) { | |
| stack.push(node.right); | |
| } | |
| node = node.left; | |
| } | |
| } | |
| public void inorder(Node root) { | |
| Stack<Node> stack = new Stack<Node>(); | |
| Node node = root; | |
| while (!stack.isEmpty() || node != null) { | |
| if (node == null) { | |
| // No need to explore | |
| node = stack.pop(); | |
| visit(node); | |
| node = node.right; | |
| } else { | |
| // Explore more | |
| stack.push(node); | |
| node = node.left; | |
| } | |
| } | |
| } | |
| public void postorder(Node node) { | |
| Stack<Node> stack = new Stack<Node>(); | |
| stack.push(node); | |
| Node prevNode = null; | |
| while (!stack.isEmpty()) { | |
| Node curNode = stack.peek(); | |
| if (prevNode == null || prevNode.left == curNode || prevNode.right == curNode) { | |
| // Come from parent | |
| if (curNode.left != null) { | |
| stack.push(curNode.left); | |
| } else if (curNode.right != null) { | |
| stack.push(curNode.right); | |
| } | |
| } else if (prevNode == curNode.left) { | |
| // Back from left child | |
| if (curNode.right != null) { | |
| stack.push(curNode.right); | |
| } | |
| } else { | |
| // Back from right child or stay (which means there is no child | |
| // to be visited). Either way, it means no more explore. | |
| visit(curNode); | |
| stack.pop(); | |
| } | |
| prevNode = curNode; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment