/** * BSTTest.java * Code to exercise the BST class. * Uses a binary search tree with string tokens as keys and * integers as values. * * @author Tom Cormen, minor modifications by Scot Drysdale */ import java.util.Scanner; public class BSTTest { public static void main(String[] args) { BST bst = new BST(); Scanner input = new Scanner(System.in); char command; String key; Integer value; BST.Node x = null; do { System.out.print("Command (? for help): "); command = input.next().charAt(0); switch (command) { case 'q': // quit System.out.println("Bye"); break; case 'c': // create an empty tree bst = new BST(); break; case 'i': // insert key = input.next(); value = input.nextInt(); bst.insert(key, value); break; case 'P': // print if (bst.isEmpty()) System.out.println("Tree is empty"); else System.out.print(bst); break; case 'f': // search key = input.next(); x = bst.search(key); if (x == null) System.out.println("Not found"); break; case 'r': // remove if (x != null) bst.remove(x); break; case 'e': // example bst = new BST(); bst.insert("O", 15); bst.insert("E", 5); bst.insert("P", 16); bst.insert("C", 3); bst.insert("L", 12); bst.insert("T", 20); bst.insert("J", 10); bst.insert("M", 13); bst.insert("R", 18); bst.insert("W", 23); bst.insert("F", 6); bst.insert("G", 7); break; case 's': // successor if (x != null) { BST.Node y = bst.successor(x); if (y == null) System.out.println("no successor"); else System.out.println(y); } break; case 'p': // predecessor if (x != null) { BST.Node y = bst.predecessor(x); if (y == null) System.out.println("no predecessor"); else System.out.println(y); } break; case 'n': // minimum if (x != null) System.out.println(bst.minimum(x)); break; case 'x': // maximum if (x != null) System.out.println(bst.maximum(x)); break; case 't': // get root x = bst.getRoot(); break; case '?': // print commands System.out.println("c create\ni insert\nr remove\nf find\nP print\ne example\ns successor\nr predecessor\nn minimum\nx maximum\nt get root\n?q quit\n? help\n"); break; default: System.out.println("Huh?"); break; } } while (command != 'q'); } }