-
Notifications
You must be signed in to change notification settings - Fork 1
/
109.cpp
53 lines (43 loc) · 1.21 KB
/
109.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
// 109. Convert Sorted List to Binary Search Tree - https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree
#include "bits/stdc++.h"
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
ListNode* next(ListNode* node) {
return node->next;
}
// [start, finish)
TreeNode* helper(ListNode* head, ListNode* tail) {
if (head == tail) { return nullptr; }
ListNode* slow = head;
ListNode* fast = head;
while (fast != tail && fast->next != tail) {
slow = next(slow);
fast = next(next(fast));
}
TreeNode* root = new TreeNode(slow->val);
root->left = helper(head, slow);
root->right = helper(slow->next, tail);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
return helper(head, nullptr);
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}