public static void main(String[] args) { BST<String> tree = new BST<String>(); tree.insert("George"); tree.insert("Michael"); tree.insert("Tom"); tree.insert("Adam"); tree.insert("Jones"); tree.insert("Peter"); tree.insert("Daniel"); System.out.print("Inorder sort: "); tree.inorder(); System.out.print("\nPostorder sort: "); tree.postorder(); System.out.print("\nPreorder sort: "); tree.preorder(); System.out.println("\n The number of nodes is " + tree.getSize()); System.out.println("Is Peter in the tree: " + tree.search("Peter")); System.out.print("Path from root to Peter: "); ArrayList<TreeNode<String>> path = tree.path("Peter"); for (int i = 0; i < path.size(); i++) System.out.print(path.get(i).elem + " "); System.out.println(); tree.delete("Jones"); System.out.println("\n The number of nodes is " + tree.getSize()); System.out.println("Is Peter in the tree: " + tree.search("Peter")); System.out.print("Inorder sort: "); tree.inorder(); }
public static void main(String[] args) throws Exception { BST T = new BST(); // an empty BST try { System.out.println(T.findMin()); // Exception occurs System.out.println(T.findMax()); // will not be executed } catch (NoSuchElementException e) { System.out.println(e); } // Sample BST as shown in Lecture T.insert(15); T.insert(23); T.insert(6); T.insert(71); T.insert(50); T.insert(4); T.insert(7); T.insert(5); System.out.println(T.search(71)); // found, 71 System.out.println(T.search(7)); // found, 7 System.out.println(T.search(22)); // not found, -1 try { System.out.println(T.findMin()); // 4 System.out.println(T.findMax()); // 71 } catch (NoSuchElementException e) { System.out.println(e); // will not be executed } System.out.println(T.successor(23)); // 50 System.out.println(T.successor(7)); // 15 System.out.println(T.successor(71)); // -1 System.out.println(T.predecessor(23)); // 15 System.out.println(T.predecessor(7)); // 6 System.out.println(T.predecessor(71)); // 50 T.inorder(); // The BST: 4, 5, 6, 7, 15, 23, 50, 71 System.out.println("Deleting 5"); T.delete(5); System.out.println("Deleting 71"); T.delete(71); System.out.println("Deleting 15"); T.delete(15); T.inorder(); // The BST: 4, 6, 7, 23, 50 }