-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy patharray to bst
52 lines (40 loc) · 1.04 KB
/
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
46
47
48
49
50
51
52
/*
Given a sorted array. Write a program that creates a Balanced Binary Search Tree using array elements. If there are N elements in array,
then floor(n/2)'th element should be chosen as root and same should be followed recursively.
Input:
The first line of input contains an integer T, denoting the number of test cases. The first line of each test case is N(size of array).
The second line of each test case contains N input A[].
Output:
Print the preorder traversal of constructed BST.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ 10000
Example:
Input:
1
7
1 2 3 4 5 6 7
Output:
4 2 1 3 6 5 7
*/
#include<bits/stdc++.h>
using namespace std;
void partition(int a[], int l, int h){
if(l>h) return;
int r = (l + ((h-l)/2));
cout<<a[r]<<" ";
partition(a,l,r-1);
partition(a,r+1,h);
}
void arrayToBST(int a[], int n){
partition(a,0,n-1);
}
int main(){
int t; cin>>t; while(t--){
int n; cin>>n;
int a[n]; for(int i=0; i<n; i++) cin>>a[i];
arrayToBST(a,n);
cout<<'\n';
}
}