-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0109.cpp
More file actions
35 lines (34 loc) · 1.08 KB
/
Copy path0109.cpp
File metadata and controls
35 lines (34 loc) · 1.08 KB
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
class Solution {
struct record {
TreeNode *root;
ListNode *low, *high;
record(TreeNode *root, ListNode *low = nullptr, ListNode *high = nullptr)
: root(root), low(low), high(high) {}
};
ListNode *get_mid(ListNode *list, ListNode *end) {
ListNode *slow, *fast;
slow = fast = list;
while (fast != end && fast->next != end) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
public:
TreeNode *sortedListToBST(ListNode *head) {
stack<record> st;
TreeNode *tree = new TreeNode(INT_MIN), *t;
st.push({tree, head, nullptr});
while (!st.empty()) {
record r = st.top();
st.pop();
while (r.low != r.high) {
ListNode *mid = get_mid(r.low, r.high);
(mid->val >= r.root->val ? r.root->right : r.root->left) = t = new TreeNode(mid->val);
st.push({r.root = t, mid->next, r.high});
r.high = mid;
}
}
return tree->right;
}
};