From 550a49b794af9a354a8b3d72e5424294ec4481f0 Mon Sep 17 00:00:00 2001 From: Stackingrule <38368554+Stackingrule@users.noreply.github.com> Date: Mon, 21 Dec 2020 15:54:57 +0800 Subject: [PATCH] feat:add Solution.cpp for 0109.Convert Sorted List to Binary Search Tree --- .../Solution.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/Solution.cpp 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