本人电子系,只为一学生。心喜计算机,小编以怡情。
给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
注意事项
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;
}
介绍如何将一个已排序的数组转换成一棵高度平衡的二叉搜索树,并提供了具体的实现代码。通过递归的方式,选取中间节点作为根节点,以此来确保二叉树的高度尽可能平衡。
1623

被折叠的 条评论
为什么被折叠?



