Node class for tree
class Node{ int data; Node left; Node right; }=========================================================================
Case 1: pre-order
Recursive
public static void preOrderRecursive(Node root){ if(root == null) return; System.out.print(root.data + " "); preOrderRecursive(root.left); preOrderRecursive(root.right); }NON-Recursive
public static void preOrderIterative(Node root){ if(root == null) return; Stack<Node> unvisited = new Stack<Node>(); unvisited.push(root); while(!unvisited.isEmpty()){ Node node = unvisited.pop(); System.out.print(node.data + " "); if(node.right != null) unvisited.push(node.right); if(node.left != null) unvisited.push(node.left); } }=========================================================================
Case 2: in-order
Recursive
public static void inOrderRecursive(Node root){ if(root == null) return; inOrderRecursive(root.left); System.out.print(root.data + " "); inOrderRecursive(root.right); }NON-Recursive
public static void inOrderIterative(Node root){ if(root == null) return; Stack<Node> unvisited = new Stack<Node>(); while(!unvisited.isEmpty() || root != null){ if(root != null){ unvisited.push(root); root = root.left; }else{ root = unvisited.pop(); System.out.print(root.data + " "); root = root.right; } } }=========================================================================
Case 3: post-order
Recursive
public static void postOrderRecursive(Node root){ if(root == null) return; postOrderRecursive(root.left); postOrderRecursive(root.right); System.out.print(root.data + " "); }NON-Recursive
public static void postOrderIterative(Node root){ if(root == null) return; Stack<Node> finalStack = new Stack<Node>(); Stack<Node> tempStack = new Stack<Node>(); tempStack.push(root); while(!tempStack.isEmpty()){ Node node = tempStack.pop(); finalStack.push(node); if(node.left != null) tempStack.push(node.left); if(node.right != null) tempStack.push(node.right); } while(!finalStack.isEmpty()){ Node node = finalStack.pop(); System.out.print(node.data + " "); } }