when building tree from post and inorder traversal why we have build the right subtree and then the left subtree
when i was submitiing the code
this was working
–>
Node* root=new Node(post[(*i)]);
int index=-1;
for(int j=s;s<=e;j++){
if(in[j]==post[(*i)]){
index=j;
break;
}
}
(*i)–;
root->right=buildtree(in,post,index+1,e,i);
root->left=buildtree(in,post,s,index-1,i);
return root;
}
Node *buildTree(int in[], int post[], int n) {
if(n==0 ){
return NULL;
}
int i=n-1;
Node* head=buildtree(in,post,0,n-1,&i);
return head;
}
this was not working–>
Node* buildtree(int in[],int post[],int s,int e,int i){
// static int i=n;
if(s>e){
return NULL;
}
Node root=new Node(post[(*i)]);
int index=-1;
for(int j=s;s<=e;j++){
if(in[j]==post[(*i)]){
index=j;
break;
}
}
(*i)–;
root->left=buildtree(in,post,s,index-1,i);
root->right=buildtree(in,post,index+1,e,i);
return root;
}
Node buildTree(int in[], int post[], int n) {
if(n==0){
return NULL;
}
int i=n-1;
Node head=buildtree(in,post,0,n-1,&i);
return head;
}