-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path109.cpp
More file actions
105 lines (100 loc) · 2.71 KB
/
109.cpp
File metadata and controls
105 lines (100 loc) · 2.71 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// O(NlogN)
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(!head)
return NULL;
ListNode* fast = head;
ListNode* slow = head;
ListNode* prev = NULL;
while(fast->next && fast->next->next){
fast = fast->next->next;
prev = slow;
slow = slow->next;
}
TreeNode* root = new TreeNode(slow->val);
if(prev==NULL){
if(fast->next == NULL)
return root;
root->right = sortedListToBST(slow->next);
return root;
}
prev->next = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
};
// Second Approach O(n) - time;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
ListNode* Node;
int length(ListNode* curr){
int count = 0;
while(curr){
count++;
curr = curr->next;
}
return count;
}
TreeNode* convert(int l, int r){
if(l>r)
return NULL;
int mid = l+ (r-l)/2;
auto left = convert(l,mid-1);
TreeNode* root = new TreeNode(Node->val);
root->left = left;
Node = Node->next;
root->right = convert(mid+1,r);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
if(!head)
return NULL;
Node = head;
int n = length(head);
return convert(0,n-1);
}
};