//Someone please explain why the code is showing segmentation fault. The code is for preorder to postorder traversal. I'm making a BST from preorder then printing in post order. Please tell. Thanks.
#include<bits/stdc++.h>
#include<limits.h>
using namespace std;
struct Node{
int data;
struct Node *left=NULL;
struct Node *right=NULL;
};
struct Node *newnode(int data){
struct Node *newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->data = data;
newnode->left=newnode->right=NULL;
}
struct Node *createbstutil(int pre[],int size,int *preindex,int key,int min,int max){
if(*preindex>=size){
return NULL;
}
struct Node *root=NULL;
if(key>min && key<max){
root = newnode(key);
*preindex+=1;
if(*preindex<size){
root->left=createbstutil(pre,size,preindex,pre[*preindex],min,key);
root->right=createbstutil(pre,size,preindex,pre[*preindex],key,max);
}
}
return root;
}
struct Node *createbst(int pre[],int size){
int preindex=0;
return createbstutil(pre,size,&preindex,pre[0],INT_MIN,INT_MAX);
}
int postorder(struct Node *root){
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
int main(){
int t,i,n;
cin>>t;
while(t--){
cin>>n;
int pre[n]={0};
for(i=0;i<n;i++)
cin>>pre[i];
struct Node *root= createbst(pre,n);
postorder(root);
}
return 0;
}