Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created July 6, 2014 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislukkk/be47c3281a3911c10475 to your computer and use it in GitHub Desktop.
Save chrislukkk/be47c3281a3911c10475 to your computer and use it in GitHub Desktop.
CareerCup_4.3 - Build bst with minimum height
package Chapter4;
public class MinHeightBST {
public static <T extends Comparable<T>> BST<T> createBST(T[] array) {
return new BST<>(buildBST(array, 0, array.length - 1));
}
private static <T extends Comparable<T>> TreeNode<T> buildBST(T[] array, int lo, int hi) {
if(lo > hi) return null;
int mid = hi - (hi - lo)/2;
TreeNode<T> node = new TreeNode<T>(array[mid]);
node.left = buildBST(array, lo, mid - 1);
node.right = buildBST(array, mid + 1, hi);
return node;
}
private static <T extends Comparable<T>> void inOrderPrint(TreeNode<T> n) {
if(n == null) return;
inOrderPrint(n.left);
System.out.print(n.key + "; ");
inOrderPrint(n.right);
}
public static void main(String[] args) {
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
BST<Integer> bst = createBST(array);
inOrderPrint(bst.root());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment