Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
class Solution {
public:
TreeNode* createTree(vector<int>& nums,int left,int right)
{
if(left>right)
return NULL;
int mid = (left+right)>>1;
TreeNode* leftNode = createTree(nums,left,mid-1); //创建左子树
TreeNode* rightNode = createTree(nums,mid+1,right);//创建右子树
TreeNode* node = new TreeNode(nums[mid]);
node->left = leftNode;
node->right = rightNode;
return node;
}
TreeNode* sortedListToBST(ListNode* head) {
vector<int> nums;
ListNode* p = head;
while(p!=NULL)
{
nums.push_back(p->val);
p = p->next;
}
return createTree(nums,0,nums.size()-1);
}
};