给定一个元素各不相同的有序序列int[] vals(升序排列),请编写算法创建一棵高度最小的二叉查找树,并返回二叉查找树的高度。
import java.util.*; public class MinimalBST { public int buildMinimalBST(int[] vals) { // write code here if(vals.length==0) return 0; if(vals.length==1) return 1; int rootIndex = vals.length/2; int [] left = Arrays.copyOfRange(vals,0,rootIndex); int [] right = Arrays.copyOfRange(vals,rootIndex+1,vals.length); return Math.max(buildMinimalBST(left),buildMinimalBST(right))+1; } }
import java.util.*; public class MinimalBST { public int buildMinimalBST(int[] vals) { return getHeigh(buildTree(vals,0,vals.length-1)); } private TreeNode buildTree(int[] array,int from,int to){ if(from>to)return null; int middleIndex=from+(to-from)/2; TreeNode root=new TreeNode(array[middleIndex]); root.left=buildTree(array,from,middleIndex-1); root.right=buildTree(array,middleIndex+1,to); return root; } private int getHeigh(TreeNode root){ if(root==null)return 0; int left=getHeigh(root.left); int right=getHeigh(root.right); return Math.max(left,right)+1; } } class TreeNode{ public int val; public TreeNode left; public TreeNode right; public TreeNode(int val){ this.val=val; } }
import java.util.*; public class MinimalBST { public int buildMinimalBST(int[] vals) { return BSTLength(vals, 0, vals.length - 1); } public static int BSTLength(int[] arr, int left, int right){ if (left > right){ return 0; } if (left == right){ return 1; } int middle = (left + right) / 2; int lLength = BSTLength(arr, left, middle - 1); int rLength = BSTLength(arr, middle + 1, right); return lLength > rLength ? (lLength + 1) : (rLength + 1); } }
import java.util.*; public class MinimalBST { public int buildMinimalBST(int[] vals) { // write code here return build(vals, 0, vals.length - 1); } private int build(int[] vals, int start, int end) { if (end < start) { return 0; } else { int mid = (start + end) / 2; int leftHeight = build(vals, start, mid - 1); int rightHeight = build(vals, mid + 1, end); return Math.max(leftHeight, rightHeight) + 1; } } }
TreeNode createBST( int[] vals, int start, int end, Height height )
TreeNode createBST( int[] vals, int start, int end ){
if( start>end ) {
return null;
}
TreeNode root = new TreeNode();
int mid = (start+end)/2;
root.val = vals[mid];
root.left = createBST(vals,start,mid-1);
root.right = createBST(vals,mid+1,end);
return root;
}
import java.util.*;
//查询二叉树的意思是,对于每一个结点,它的左结点都小于它,右结点都大于它。
//要实现一个高度最小的查询二叉树,就是尽量让每一个结点都占满(除了叶结点,为满二叉树)。
//已知结点个数,求高度最小的查询二叉树高度,只要设计一个for循环,每次循环的次数为2的n次方,
//n每次循环结束自增1。 public class MinimalBST {
public int buildMinimalBST(int[] vals) {
int length = vals.length;
int high = 0;
int n = 0;
while(length>0){
high++;
for(int i=0;i<Math.pow(2,n);i++){
length--;
}
n++;
}
return high;
}
}