1,并没有把高度和建表结合了。而是最后才算。下一次可以想想怎么结合到一块去。
1,建表(参考自书本)
private static TreeNode createMinimalBST(int arr[], int start, int end){ if (end < start) { return null; } int mid = (start + end) / 2; TreeNode n = new TreeNode(arr[mid]); n.setLeftChild(createMinimalBST(arr, start, mid - 1)); n.setRightChild(createMinimalBST(arr, mid + 1, end)); return n; } public static TreeNode createMinimalBST(int array[]) { return createMinimalBST(array, 0, array.length - 1); }
2,求高度:
public class MinimalBST { public int buildMinimalBST(int[] vals) { // write code here return (int)(Math.ceil(Math.log(vals.length+1)/Math.log(2))); } }