import ch08.trees.BinarySearchTree; import support.BSTNode; public class Balance { private static final int INORDER = 1; private static BinarySearchTree tree; private static Long[] array; public static void main(String[] args) { // Create a fully UNbalanced tree and print its height tree = new BinarySearchTree(); for (int i=0; i<15; i++) tree.add(new Long(i)); System.out.println("The unbalanced height is " + height(tree.getRoot())); // Balance the tree and print its height balance(); System.out.println("The balanced height is " + height(tree.getRoot())); } private static int height(BSTNode tree) { if (tree == null) throw new RuntimeException("Height of empty tree undefined"); return recHeight(tree); } private static int recHeight(BSTNode tree) { if (tree.getLeft()==null && tree.getRight()==null) return 0; int max = 0; if (tree.getLeft()!=null) { int leftHeight = recHeight(tree.getLeft()); if (leftHeight > max) max = leftHeight; } if (tree.getRight()!=null) { int rightHeight = recHeight(tree.getRight()); if (rightHeight > max) max = rightHeight; } return 1 + max; } private static void balance() { int n = tree.reset(INORDER); array = new Long[n]; for (int i=0; i(); insertTree(0, n-1); } private static void insertTree(int lo, int hi) { if (lo <= hi) { int mid = (lo+hi)/2; tree.add(array[mid]); insertTree(lo, mid-1); insertTree(mid+1, hi); } } } // Local Variables: // compile-command: "export CLASSPATH=/a/dale-dataStructures/ajgFiles/:.; \ // (javac Balance.java && java Balance)" // End: