--- tags: leetcode --- # [109. Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode *sortedListToBST(ListNode *head) { if (head == nullptr) { return nullptr; } if (head->next == nullptr) { return new TreeNode(head->val); } ListNode *preSlow = nullptr, *slow = head, *fast = head; while (fast != nullptr && fast->next != nullptr) { preSlow = slow; slow = slow->next; fast = fast->next->next; } ListNode *head2 = slow->next; slow->next = nullptr; preSlow->next = nullptr; TreeNode *node = new TreeNode(slow->val); node->left = sortedListToBST(head); node->right = sortedListToBST(head2); return node; } }; ``` ## Time Complexity $O(nlogn)$ * $n$ is the number of nodes in the singly linked list referenced by `head`. ## Space Complexity $O(n)$ # Miscellaneous <!-- # Test Cases ``` [-10,-3,0,5,9] ``` ``` [] ``` ``` [0] ``` ``` [1,3] ``` ``` [1,2,3] ``` ``` [-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] ``` -->