Problem:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Explanation:
将一个递增数组转变为平衡BST。
My Thinking:
为了达到平衡,每次取数组中位于中间的数作为根结点,左半边的数组继续递归作为左孩子,右半边的数组作为右孩子即可。
My Solution:
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length==0)
return null;
return create(nums,0,nums.length-1);
}
public TreeNode create(int[] nums,int low,int high){
if(low<=high){
int pivot=(high+low)/2;//取一半的位置
TreeNode node=new TreeNode(nums[pivot]);
node.left=create(nums,low,pivot-1);
node.right=create(nums,pivot+1,high);
return node;
}
return null;
}
}
Optimum Thinking:
Optimum Solution: