Created
July 6, 2014 17:00
-
-
Save chrislukkk/be47c3281a3911c10475 to your computer and use it in GitHub Desktop.
CareerCup_4.3 - Build bst with minimum height
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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