-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimal_tree_from_sorted_array.cpp
More file actions
108 lines (90 loc) · 1.79 KB
/
minimal_tree_from_sorted_array.cpp
File metadata and controls
108 lines (90 loc) · 1.79 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
106
107
108
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<vector>
using namespace std;
struct node{
int data;
struct node *left, *right;
};
struct node *root=NULL;
struct node *new_node(int data){
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=data;
temp->left=NULL;
temp->right=NULL;
return temp;
}
struct node *insert(struct node *node, int data){
if(node==NULL){
//root = new_node(data);
return new_node(data);
}
if(data < node->data){
node->left=insert(node->left, data);
}
else{
node->right=insert(node->right, data);
}
return node;
}
void in_order(struct node *root){
if(root!=NULL){
in_order(root->left);
cout<<root->data<<" ";
in_order(root->right);
}
}
void pre_order(struct node *root){
if(root!=NULL){
cout<<root->data<<" ";
pre_order(root->left);
pre_order(root->right);
}
}
void post_order(struct node *root){
if(root!=NULL){
post_order(root->left);
post_order(root->right);
cout<<root->data<<" ";
}
}
struct node* minimal_bst_utils(vector<int> &arr, int start, int end){
if(end<start){
return NULL;
}
struct node *node;
int mid=(start+end)/2;
//cout<<arr[mid]<<endl;
node=new_node(arr[mid]);
node->left=minimal_bst_utils(arr,start,mid-1);
node->right=minimal_bst_utils(arr,mid+1,end);
return node;
}
void minimal_bst(vector<int> &arr){
int size=arr.size();
root=minimal_bst_utils(arr, 0, size-1);
}
int main(){
int n;
cin>>n;
vector<int> arr(n);
for(int i=0;i<n;++i){
cin>>arr[i];
}
minimal_bst(arr);
/*
struct node *root=NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
*/
in_order(root);cout<<endl;
pre_order(root);cout<<endl;
post_order(root);cout<<endl;
return 0;
}