题目:
Given a singly linked list 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 *sortedListToBST(ListNode *head) {
vector<int> num;
while(head!=NULL)
{
num.push_back(head->val);
head=head->next;
}
return build(num,0,num.size()-1);
}