Source of MakeBST.java


  1: import java.util.Scanner;

  3: /**
  4:  * A program to test the BinarySearchTree class.
  5:  *
  6:  * @author Mark Young (A00000000)
  7:  */
  8: public class MakeBST {

 10:     public static void main(String[] args) {
 11:         // create and populate the BST
 12:         BinarySearchTree<Integer> bst = new BinarySearchTree<>();
 13:         insertAll(bst, new int[]{31, 8, 12, 99, 18, 4, 15, 55, 42, 11, 99});
 14:         System.out.println(bst);
 15:         pause();
 16:         
 17:         // check the BST for some values
 18:         for (int i = 1; i <= 10; ++i) {
 19:             System.out.println("BST contains " + i + "? "
 20:                 + bst.contains(i));
 21:         }
 22:         pause();

 24:         System.out.println("\n\nDeleting 11 (no children)");
 25:         bst.delete(11);
 26:         System.out.println(bst);
 27:         pause();
 28:         System.out.println("\n\nDeleting 55 (one child)");
 29:         bst.delete(55);
 30:         System.out.println(bst);
 31:         pause();
 32:         System.out.println("\n\nDeleting 31 (two children -- promote a leaf)");
 33:         bst.delete(31);
 34:         System.out.println(bst);
 35:         pause();
 36:         System.out.println("\n\nDeleting 8 (two children "
 37:                 + "-- promote node with child)");
 38:         bst.delete(8);
 39:         System.out.println(bst);
 40:         pause();
 41:         System.out.println("\n\nDeleting 77 (not there)");
 42:         bst.delete(77);
 43:         System.out.println(bst);
 44:         pause();
 45:     }

 47:     /**
 48:      * Inserts every integer from the given array into the given BST.
 49:      *
 50:      * @param bst the BST to insert into.
 51:      * @param arr the numbers to insert into the BST.
 52:      */
 53:     private static void insertAll(BinarySearchTree<Integer> bst, int[] arr) {
 54:         for (int num : arr) {
 55:             if (bst.insert(num)) {
 56:                 System.out.println("Inserted " + num);
 57:             } else {
 58:                 System.out.println("Failed to insert " + num);
 59:             }
 60:         }
 61:     }
 62:     
 63:     private static final Scanner KBD = new Scanner(System.in);

 65:     /**
 66:      * Wait for the user to press the enter key. Includes a prompt and before-
 67:      * after blank lines.
 68:      */
 69:     private static void pause() {
 70:         System.out.println();
 71:         System.out.print("Press enter...");
 72:         KBD.nextLine();
 73:         System.out.println();
 74:     }

 76: }