-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathArray to BST.cpp
60 lines (51 loc) · 1011 Bytes
/
Array to BST.cpp
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
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *left;
Node *right;
Node(int d){
data = d;
left = nullptr;
right = nullptr;
}
};
void sortedBST(int);
Node* _sortedBST(int[], int, int);
void preOrder(Node*);
int main(){
int t, n;
cin >> t;
while(t--){
cin >> n;
sortedBST(n);
cout << endl;
}
return 0;
}
void sortedBST(int n){
int arr[n];
Node *root = nullptr;
for(int i = 0; i < n; i++)
cin >> arr[i];
root = _sortedBST(arr, 0, n - 1);
preOrder(root);
}
void preOrder(Node *root){
if(root){
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
}
Node* _sortedBST(int arr[], int l, int r){
if(l > r)
return nullptr;
else{
int m = (l + r) / 2;
Node *root = new Node(arr[m]);
root->left = _sortedBST(arr, l , m - 1);
root->right = _sortedBST(arr, m + 1, r);
return root;
}
}