Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
是一道比较简单的递归题。
像二分查找一样,不断地把升序数组切半,分别看做新的数组,再切半。。。
这边要注意:如果low > high, 返回空结点。
public TreeNode buildTree(int[] num, int low, int high){
if(low>high)
return null;
int mid = low+(high-low)/2;
TreeNode node = new TreeNode(num[mid]);
node.left = buildTree(num,low,mid-1);
node.right = buildTree(num,mid+1,high);
return node;
}
public TreeNode sortedArrayToBST(int[] num) {
return buildTree(num,0,num.length-1);
}

3421

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



