TreeNode *BST(ListNode *begin, ListNode *end) {
if (begin == end)
return nullptr;
ListNode *fast = begin, *slow = begin;
while (fast->next != end) {
fast = fast->next;
if (fast->next == end)
break;
fast = fast->next;
slow = slow->next;
}
auto *mid = new TreeNode(slow->val);
mid->left = BST(begin, slow);
mid->right = BST(slow->next, end);
return mid;
};
TreeNode *sortedListToBST(ListNode *head) {
if (head == nullptr)
return nullptr;
else if (head->next == nullptr)
return new TreeNode(head->val);
return BST(head, nullptr);
}