本人电子系,只为一学生。心喜计算机,小编以怡情。
给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
注意事项
There may exist multiple valid solutions, return any of them.
public TreeNode sortedArrayToBST(int[] A) {//递归建立
if (A.length==0) return null;
return buildtree(A,0,A.length-1);
}
public TreeNode buildtree (int []A,int start,int end){
int mid=(start+end)/2;
TreeNode root=new TreeNode(A[mid]);
if(start<=mid-1)
root.left=buildtree(A,start,mid-1);
if(mid+1<=end)
root.right=buildtree(A,mid+1,end);
return root;
}