diff --git a/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/Solution.cpp b/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/Solution.cpp new file mode 100644 index 0000000000000..96671a35a8875 --- /dev/null +++ b/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/Solution.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + TreeNode* sortedListToBST(ListNode* head) { + if (!head) return nullptr; + if (!head->next) return new TreeNode(head->val); + ListNode *fast = head, *slow = 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 *cur = new TreeNode(slow->val); + if (head != slow) cur->left = sortedListToBST(head); + cur->right = sortedListToBST(fast); + return cur; + } +}; \ No newline at end of file