-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlitobst.cpp
More file actions
39 lines (38 loc) · 720 Bytes
/
litobst.cpp
File metadata and controls
39 lines (38 loc) · 720 Bytes
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
//Sorted linked list to BST
#define pb push_back
void find(int x,TreeNode* &ans)
{
if(ans==NULL)
{
ans=new TreeNode(x);
return ;
}
if(x>ans->val)
{
find(x,ans->right);
}
if(x<ans->val)
{
find(x,ans->left);
}
}
void rec(vector<int>&v,int lo,int hi,TreeNode* &ans)
{
if(lo>hi)
return;
int mid=(lo+hi)/2;
find(v[mid],ans);
rec(v,lo,mid-1,ans);
rec(v,mid+1,hi,ans);
}
TreeNode* Solution::sortedListToBST(ListNode* A) {
vector<int>v;
TreeNode* ans=NULL;
while(A)
{
v.push_back(A->val);
A=A->next;
}
rec(v,0,v.size()-1,ans);
return ans;
}