/* * Jeremy Lipschutz * * A class representing a tree of integers */ public class IntTree { private IntTreeNode overallRoot; // Constructs an empty tree public IntTree() { overallRoot = null; /* You can change this constructor to add your own special nodes, we'll talk more about modifying trees on Wednesday overallRoot = new IntTreeNode(17); overallRoot.left = new IntTreeNode(41); overallRoot.right = new IntTreeNode(9); overallRoot.left.left = new IntTreeNode(29); overallRoot.left.right = new IntTreeNode(6); overallRoot.right.left = new IntTreeNode(81); overallRoot.right.right = new IntTreeNode(40); */ } // Prints the preorder traversal of the current tree public void printPreorder() { System.out.print("preorder: "); printPreorder(overallRoot); System.out.println(); } // Prints the preorder traversal of the tree represented by the // given root of it private void printPreorder(IntTreeNode root) { if(root != null) { System.out.print(root.data + " "); printPreorder(root.left); printPreorder(root.right); } } // Prints the preorder traversal of the current tree public void printInOrder() { printInOrder(overallRoot); } // Prints the in order traversal of the tree represented by the // given root of it private void printInOrder(IntTreeNode root) { if(root != null) { printInOrder(root.left); System.out.print(root.data + " "); printInOrder(root.right); } } // Prints the preorder traversal of the current tree public void printPostOrder() { printPostOrder(overallRoot); } // Prints the post order traversal of the tree represented by the // given root of it private void printPostOrder(IntTreeNode root) { if(root != null) { printPostOrder(root.left); printPostOrder(root.right); System.out.print(root.data + " "); } } // Returns whether or not a value is contained within the current // tree public boolean contains(int value) { return contains(overallRoot, value); } // Returns whether or not a value is contained within the // tree represented by the given root of it private boolean contains(IntTreeNode root, int value) { if(root == null) { // The empty tree holds no values, so the value can't be // in this tree return false; } else { // A value is in this tree if it matches the data of the // root, or is in either of the subtrees return root.data == value || contains(root.left, value) || contains(root.right, value); } } }