// Stuart Reges, 2/22/06 // modified by Marty Stepp 2/23/09 // // A basic binary tree class that includes methods to construct a random tree // of ints and to print its data using pre-, in-, or post-order traversals. public class IntTree { private IntTreeNode overallRoot; // Constructs an empty binary tree (null root). public IntTree() { this(null); } // Constructs a binary tree with the given node as its root. public IntTree(IntTreeNode root) { overallRoot = root; } // Constructs a perfect binary tree of the given height with random // data values between 0 and 99 inclusive. // Throws an IllegalArgumentException if the height is less than 0. public IntTree(int height) { if (height < 0) { throw new IllegalArgumentException(); } overallRoot = randomTree(height); } // Constructs and returns a reference to a full binary tree of height h // with random data values between 0 and 99 inclusive. // Precondition: height >= 0 private IntTreeNode randomTree(int h) { if (h == 0) { return null; } else { int n = (int) (Math.random() * 100); IntTreeNode node = new IntTreeNode(n); node.left = randomTree(h - 1); node.right = randomTree(h - 1); return node; } } // Prints an in-order traversal of this tree's elements, separated by spaces. // A blank line of output is produced when the tree is empty. public void print() { print(overallRoot); System.out.println(); // end the line of output } // Prints an in-order traversal of the given root node's elements, // separated by spaces. No output is produced for an empty tree. private void print(IntTreeNode root) { if (root != null) { print(root.left); System.out.print(root.data + " "); print(root.right); } } // Prints a pre-order traversal of this tree's elements, separated by spaces. // A blank line of output is produced when the tree is empty. public void printPreOrder() { printPreOrder(overallRoot); System.out.println(); // end the line of output } // Prints a pre-order traversal of the given root node's elements, // separated by spaces. No output is produced for an empty tree. private void printPreOrder(IntTreeNode root) { if (root != null) { System.out.print(root.data + " "); printPreOrder(root.left); printPreOrder(root.right); } } // Prints a pre-order traversal of this tree's elements, separated by spaces. // A blank line of output is produced when the tree is empty. public void printPostOrder() { printPostOrder(overallRoot); System.out.println(); // end the line of output } // Prints a post-order traversal of the given root node's elements, // separated by spaces. No output is produced for an empty tree. private void printPostOrder(IntTreeNode root) { if (root != null) { printPostOrder(root.left); printPostOrder(root.right); System.out.print(root.data + " "); } } }