-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path109.ConvertSortedListToBinarySearchTree.cpp
More file actions
43 lines (43 loc) · 1.08 KB
/
109.ConvertSortedListToBinarySearchTree.cpp
File metadata and controls
43 lines (43 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
36
37
38
39
40
41
42
43
/**
* 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(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> vec;
TreeNode* list2bst(int start, int end){
if(end == start)
return NULL;
if(end-start == 1)
return new TreeNode(vec[start]->val);
int mid = start + (end-start)/2;
TreeNode* left = list2bst(start, mid);
TreeNode* right = list2bst(mid+1, end);
TreeNode* root = new TreeNode(vec[mid]->val);
root->left = left;
root->right = right;
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
if(head == NULL)
return NULL;
while(head != NULL){
vec.push_back(head);
head = head->next;
}
return list2bst(0, vec.size());
}
};