// An IntSearchTree object represents an entire binary search tree of ints. // Class invariant: // - nodes to the left of a root have smaller values // - nodes to the right of a root have larger values // - there are no duplicates public class IntSearchTree { private IntTreeNode overallRoot; // Constructs an empty binary tree public IntSearchTree() { overallRoot = null; } // Constructs a binary tree with the given node as its root. public IntSearchTree(IntTreeNode overallRoot) { this.overallRoot = overallRoot; } // returns true if the value is found in this tree, false otherwise public boolean contains(int value) { return contains(overallRoot, value); } private boolean contains(IntTreeNode root, int value) { if (root == null) { return false; } else if (root.data == value) { return true; } else if (value < root.data) { return contains(root.left, value); } else { return contains(root.right, value); } } // adds a value to the bst // post: the tree is still a valid bst public void add(int value) { overallRoot = add(overallRoot, value); } private IntTreeNode add(IntTreeNode root, int value) { if (root == null) { root = new IntTreeNode(value); //return root; // useful for visualizing with jGRASP debugger } else if (value < root.data) { root.left = add(root.left, value); } else if (value > root.data) { root.right = add(root.right, value); } return root; } // Prints a pre-order traversal of this tree. public void printPreOrder() { printPreOrder(overallRoot); System.out.println(); } // Prints a pre-order traversal of the tree starting at the specified root private void printPreOrder(IntTreeNode root) { // implicit base case: do nothing if we reach a null root if (root != null) { System.out.print(root.data + " "); printPreOrder(root.left); printPreOrder(root.right); } } // Prints an in-order traversal of this tree. public void printInOrder() { printInOrder(overallRoot); System.out.println(); } // Prints an in-order traversal of the tree starting at the specified root private void printInOrder(IntTreeNode root) { if (root != null) { printInOrder(root.left); System.out.print(root.data + " "); printInOrder(root.right); } } // Prints a post-order traversal of this tree. public void printPostOrder() { printPostOrder(overallRoot); System.out.println(); } // Prints a post-order traversal of the tree starting at the specified root private void printPostOrder(IntTreeNode root) { if (root != null) { printPostOrder(root.left); printPostOrder(root.right); System.out.print(root.data + " "); } } }