We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 1f35106 commit 550a49bCopy full SHA for 550a49b
solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/Solution.cpp
@@ -0,0 +1,19 @@
1
+class Solution {
2
+public:
3
+ TreeNode* sortedListToBST(ListNode* head) {
4
+ if (!head) return nullptr;
5
+ if (!head->next) return new TreeNode(head->val);
6
+ ListNode *fast = head, *slow = head, *last = slow;
7
+ while (fast->next && fast->next->next) {
8
+ last = slow;
9
+ slow = slow->next;
10
+ fast = fast->next->next;
11
+ }
12
+ fast = slow->next;
13
+ last->next = nullptr;
14
+ TreeNode *cur = new TreeNode(slow->val);
15
+ if (head != slow) cur->left = sortedListToBST(head);
16
+ cur->right = sortedListToBST(fast);
17
+ return cur;
18
19
+};
0 commit comments