找中點然後採用分治法。
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head == NULL) return NULL;
if(head ->next == NULL) return new TreeNode(head->val);
auto pre = head;
auto slow = pre->next;
auto fast = slow->next;
while(fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
pre = pre->next;
}
auto next_right = slow->next;
auto root = new TreeNode(slow->val);
pre->next = nullptr;
root->left = sortedListToBST(head);
root->right = sortedListToBST(next_right);
return root;
}
};