// Allison Obourn // CSE 143 - lecture 20 // 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 IntBinarySearchTree { private IntTreeNode overallRoot; // Constructs an empty binary tree. public IntBinarySearchTree() { overallRoot = null; } // Constructs a binary tree with the given node as its root. // Note: this is hacky and just useful for testing public IntBinarySearchTree(IntTreeNode root) { overallRoot = root; } // Returns true if the value is in this tree, false otherwise. public boolean contains(int value) { return contains(overallRoot, value); } // Returns true if the value is in the tree starting at the // specified root. private boolean contains(IntTreeNode root, int value) { if(root == null) { return false; } else if(root.data == value) { return true; } else if(root.data > value) { return contains(root.left, value); } else { return contains(root.right, value); } } // Adds the given value to this BST. // Post: the tree is still a valid BST public void add(int value) { overallRoot = add(overallRoot, value); } // Adds the given value to the BST starting at the given root. // Post: the tree is still a valid BST private IntTreeNode add(IntTreeNode root, int value) { if(root == null) { root = new IntTreeNode(value); } else if(root.data > value) { root.left = add(root.left, value); } else if(root.data > value) { 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) { 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 + " "); } } }