-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy path0109.cpp
28 lines (27 loc) · 788 Bytes
/
0109.cpp
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
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
TreeNode* sortedListToBST(ListNode* head)
{
if (head == nullptr) return nullptr;
TreeNode* res;
if (head->next == nullptr)
{
res = new TreeNode(head->val);
return res;
}
ListNode* slow = head, *fast = head->next->next;
while (fast != nullptr and fast->next != nullptr)
{
slow = slow->next;
fast = fast->next->next;
}
ListNode* tmp = slow->next;
slow->next = nullptr;
res = new TreeNode(tmp->val);
res->left = sortedListToBST(head);
res->right = sortedListToBST(tmp->next);
return res;
}
};