-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertSortedListToBinarySearchTree.cpp
More file actions
76 lines (69 loc) · 1.77 KB
/
Copy pathConvertSortedListToBinarySearchTree.cpp
File metadata and controls
76 lines (69 loc) · 1.77 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//task 109
/**
* 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) {}
* };
*/
//slow, but based on previous solution - 40ms 30.3mb
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums)
{
if (nums.empty()) return NULL;
int mid(nums.size()/2);
auto start(nums.begin());
TreeNode* root = new TreeNode(nums[mid]);
vector<int>left(start, start + mid);
root->left = sortedArrayToBST(left);
vector<int>right(start + mid + 1, nums.end());
root->right = sortedArrayToBST(right);
return root;
}
TreeNode* sortedListToBST(ListNode* head)
{
if (!head) return NULL;
vector<int> container;
while(head)
{
container.push_back(head->val);
head = head->next;
}
return sortedArrayToBST(container);
}
};
//fast, recursively - 32ms 25.4mb
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head)
{
if(!head) return NULL;
if(!head->next) return new TreeNode(head->val);
ListNode* slow = head;
ListNode* fast = head->next;
ListNode* pre = new ListNode(0);
pre->next = slow;
while(fast)
{
slow = slow->next;
pre = pre->next;
fast = fast->next ? fast->next->next : NULL;
}
TreeNode* root = new TreeNode(slow->val);
pre->next = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
}