// Class to represent a basic binary tree // Includes a constructor to create a "sequential tree" which is a tree // with the values 1 through n added sequentially level by level with // no gaps in the tree. public class IntTree { private IntTreeNode overallRoot; public IntTree() { this.overallRoot = null; } // prints this tree using preorder traversal public void printPreorder() { System.out.print("preorder: "); printPreorder(overallRoot); System.out.println(); } // prints the tree with the given root using preorder traversal private void printPreorder(IntTreeNode root) { if (root != null) { // print root System.out.print(" " + root.data); // print left subtree (in preorder) printPreorder(root.left); // print right subtree (in preorder) printPreorder(root.right); } } // prints this tree using inorder traversal public void printInorder() { System.out.print("inorder: "); printInorder(overallRoot); System.out.println(); } // prints the tree with the given root using inorder traversal private void printInorder(IntTreeNode root) { if (root != null) { // print left subtree (in preorder) printInorder(root.left); // print root System.out.print(" " + root.data); // print right subtree (in preorder) printInorder(root.right); } } // prints this tree using postorder traversal public void printPostorder() { System.out.print("postorder: "); printPostorder(overallRoot); System.out.println(); } // prints the tree with the given root using postorder traversal private void printPostorder(IntTreeNode root) { if (root != null) { // print left subtree (in preorder) printPostorder(root.left); // print right subtree (in preorder) printPostorder(root.right); // print root System.out.print(" " + root.data); } } // prints the contents of this tree, one per line, // using indentation to indicate depth // output will look like this tree rotated 90 degrees public void printSideways() { printSideways(overallRoot, 0); } // prints the contents of the tree with the given root // indenting each line to at least the given level private void printSideways(IntTreeNode root, int level) { if (root != null) { printSideways(root.right, level + 1); for (int i = 0; i < level; i++) { System.out.print(" "); } System.out.println(root.data); printSideways(root.left, level + 1); } } // constructs a sequential tree with the given number of ndoes // pre: max >= 0 (throws IllegalArgumentException if not) public IntTree(int max) { if (max < 0) { throw new IllegalArgumentException("max cannot be negative"); } overallRoot = buildTree(1, max); } // if n > max, returns null // otherwise, returns a sequential tree with n at its root private IntTreeNode buildTree(int n, int max) { if (n > max) { return null; } else { IntTreeNode left = buildTree(2 * n, max); IntTreeNode right = buildTree(2 * n + 1, max); return new IntTreeNode(n, left, right); } } }