-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.cpp
62 lines (55 loc) · 1.37 KB
/
Solution.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <deque>
#include <unordered_map>
#include <cmath>
#include <queue>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
// two pointers
TreeNode* sortedListToBST(ListNode* head) {
if (head == NULL) return NULL;
if (head->next == NULL) return new TreeNode(head->val);
// at least 2 nodes
ListNode * fast = head , * slow = head;
while (fast != NULL and fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
// 1 -> 2 -> 3 -> 4 -> NULL
// ^slow ^fast
// 1 -> 2 -> 3 -> NULL
// ^s ^fast
TreeNode * res = new TreeNode(slow->val);
if (slow != head) {
ListNode * p = head;
while (p->next != slow) p = p->next;
p->next = NULL;
res->left = sortedListToBST(head);
} else {
res->left = NULL;
}
res->right = sortedListToBST(slow->next);
return res;
}
};
int main() {
Solution a;
return 0;
}