// This class represents a tree of integers public class IntTree { private IntTreeNode overallRoot; // Constructs an empty tree. public IntTree() { overallRoot = null; } // Prints the numbers in this tree in a pre-order fashion. public void printPreorder() { System.out.print("preorder:"); printPreorder(overallRoot); System.out.println(); } // Prints the numbers of the subtree rooted at root // using a pre-order traversal. private void printPreorder(IntTreeNode root) { if (root != null) { System.out.print(" " + root.data); printPreorder(root.left); printPreorder(root.right); } } // Prints the numbers in this tree in a in-order fashion. public void printInorder() { printInorder(overallRoot); } // Prints the numbers of the subtree rooted at root // using a in-order traversal. private void printInorder(IntTreeNode root) { if (root != null) { printInorder(root.left); System.out.print(" " + root.data); printInorder(root.right); } } // Prints the numbers in this tree in a post-order fashion. public void printPostorder() { printPostorder(overallRoot); } // Prints the numbers of the subtree rooted at root // using a post-order traversal. private void printPostorder(IntTreeNode root) { if (root != null) { printPostorder(root.left); System.out.print(" " + root.data); printPostorder(root.right); } } // Class that represents a single node in the tree private static class IntTreeNode { public int data; public IntTreeNode left; public IntTreeNode right; // Constructs a leaf node with given data public IntTreeNode(int data) { this(data, null, null); } // Constructs a branch node with given data, left subtree, right subtree public IntTreeNode(int data, IntTreeNode left, IntTreeNode right) { this.data = data; this.left = left; this.right = right; } } }