-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_109.cpp
More file actions
45 lines (42 loc) · 1015 Bytes
/
Copy pathP_109.cpp
File metadata and controls
45 lines (42 loc) · 1015 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>
#define fast_io \
ios::sync_with_stdio(false); \
cin.tie(nullptr);
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int _val, ListNode* _next) {
val = _val;
next = _next;
}
};
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int _val) { val = _val; }
};
TreeNode* sortedListToBST(ListNode* head) {
if (head == nullptr) {
return nullptr;
}
if (head->next == nullptr) {
return new TreeNode(head->val);
}
ListNode* dummy = new ListNode(-1, head);
ListNode* slow = dummy;
ListNode* fast = dummy;
while (fast->next != nullptr && fast->next->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
}
ListNode* right = slow->next->next;
ListNode* root = slow->next;
slow->next->next = nullptr;
slow->next = nullptr;
TreeNode* res = new TreeNode(root->val);
res->left = sortedListToBST(dummy->next);
res->right = sortedListToBST(right);
return res;
}