Source of RedBlackTreeDemo.java


  1: //RedBlackTreeDemo.java

  3: import java.util.Scanner;

  5: public class RedBlackTreeDemo
  6: {
  7:     public static void main(String[] args)
  8:     {
  9:         Scanner scnr = new Scanner(System.in);

 11:         System.out.print("Enter insert values with spaces between: ");
 12:         String userValuesStr = scnr.nextLine();
 13:         System.out.println();

 15:         // Create an RedBlackTree object and add the values
 16:         RedBlackTree tree = new RedBlackTree();
 17:         for (String value : userValuesStr.split(" "))
 18:         {
 19:             tree.insert(Integer.parseInt(value));
 20:         }

 22:         // Display the height and tree after all inserts are complete
 23:         System.out.printf("Red-black tree with %d nodes has height %d\n",
 24:                           tree.getLength(), tree.getHeight());
 25:         System.out.println(RBTPrint.treeToString(tree.getRoot()));

 27:         // Read user input to get a list of values to remove
 28:         System.out.print("Enter remove values with spaces between: ");
 29:         userValuesStr = scnr.nextLine();
 30:         System.out.println();

 32:         for (String value : userValuesStr.split(" "))
 33:         {
 34:             int toRemove = Integer.parseInt(value);
 35:             System.out.printf("Remove node %s: ", value);
 36:             if (tree.remove(toRemove))
 37:             {
 38:                 System.out.printf("Red-black tree with %d nodes has height %d\n",
 39:                                   tree.getLength(), tree.getHeight());
 40:             }
 41:             else
 42:             {
 43:                 System.out.println("*** Key not found. Tree is not changed. ***");
 44:             }
 45:         }

 47:         // Print the tree
 48:         System.out.println(RBTPrint.treeToString(tree.getRoot()));
 49:     }
 50: }