Prem_1997
9/21/2018 - 4:06 PM

bst from pre order

#include <bits/stdc++.h>
using namespace std;
struct node{
	int data;
	node*left;
	node*right;
};
node *newnode(int val){
	struct node *prem = new node;
	prem->data = val;
	prem->left = NULL;
	prem->right = NULL;
	return prem;
}
struct node *constructtree(int pre[],int *preindex,int n,int min,int max){
	if(*preindex >= n){return NULL;}
	node *root = NULL;
	int key = pre[*preindex];
	if(key > min && key < max){
		root = newnode(key);
		*preindex  = *preindex+1;
		root->left = constructtree(pre,preindex,n,min,key);
		root->right = constructtree(pre,preindex,n,key,max);
	}
	return root;
}
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];
	}
	int preindex = 0;
	node*root = constructtree(pre,&preindex,n,INT_MIN,INT_MAX);
	inorder(root);
	return 0;
}