-
Notifications
You must be signed in to change notification settings - Fork 0
/
Construct_BST_from_Preorder2.cpp
48 lines (48 loc) · 1.17 KB
/
Construct_BST_from_Preorder2.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
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node *left;
node *right;
};
node *newnode(int data){
node *temp = new node();
temp->data = data;
temp->left=NULL;
temp->right=NULL;
return temp;
}
node *construct_bst_util(int pre[], int &preindex, int key, int min, int max, int n){
if(preindex>=n)
return NULL;
node *root = NULL;
if(key>min && key<max){
root = newnode(key);
preindex++;
root->left = construct_bst_util(pre, preindex, pre[preindex], min, key, n);
root->right = construct_bst_util(pre, preindex, pre[preindex], key, max, n);
}
return root;
}
node *construct_bst(int pre[], int n){
int preindex = 0;
return construct_bst_util(pre, preindex, pre[preindex], INT_MIN, INT_MAX, n);
}
void inorder(node *root){
if(root==NULL)
return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
int main(){
int n;
cin>>n;
int pre[n];
for(int i=0;i<n;i++)
cin>>pre[i];
node *root = construct_bst(pre,n);
inorder(root);
return 0;
}
//Time Complexity: O(n)