-
Notifications
You must be signed in to change notification settings - Fork 0
/
Array to BST
45 lines (41 loc) · 886 Bytes
/
Array to BST
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
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
void solve(vector<int> &nums, vector<int> &res,int s,int e)
{
if(s>e)
return;
int mid=(s+e)/2;
int temp=nums[mid];
res.push_back(temp);
solve(nums,res,s,mid-1);
solve(nums,res,mid+1,e);
}
vector<int> sortedArrayToBST(vector<int>& nums) {
// Code here
vector<int> res;
int s=0;
int e= nums.size()-1;
solve(nums,res,s,e);
return res;
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int n;
cin >> n;
vector<int>nums(n);
for(int i = 0; i < n; i++)cin >> nums[i];
Solution obj;
vector<int>ans = obj.sortedArrayToBST(nums);
for(auto i: ans)
cout << i <<" ";
cout << "\n";
}
return 0;
} // } Driver Code Ends