题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
代码如下:
TreeNode *build(vector<int> &num,int begin,int end)
{
if(begin>end)
{
return NULL;
}
int mid=begin+(end-begin)/2;
TreeNode *root=new TreeNode(num[mid]);
root->left=root->right=NULL;
if(mid>begin)
{
root->left=build(num,begin,mid-1);
}
if(mid<end)
{
root->right=build(num,mid+1,end);
}
return root;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
int n=num.size()-1;
TreeNode *root=build(num,0,n);
return root;
}