class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(!head) return nullptr;
if(!head->next) return new TreeNode(head->val);
ListNode *slow = head, *fast = head, *last = slow;
while(fast->next && fast->next->next) {
last = slow;
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next;
last->next = nullptr;
TreeNode *root = new TreeNode(slow->val);
if(slow != head) //slow指向的是根节点,如果slow == head, 说明左侧已经没有结点了
root->left = sortedListToBST(head);
root->right = sortedListToBST(fast);
return root;
}
};