Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head)
{
if (0 == head) return 0;
if (0 == head->next) return new TreeNode(head->val);
ListNode* fast = head;
ListNode* slow = head;
ListNode* prev = head;
while (fast->next != 0 && fast->next->next !=0)
{
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
if (fast->next != 0)
{
prev = slow;
slow = slow->next;
}
fast = slow->next;
TreeNode* newNode = new TreeNode(slow->val);
slow->next = 0;
prev->next= 0;
newNode->left = sortedListToBST(head);
newNode->right = sortedListToBST(fast);
return newNode;
}
};