unable to understand last step in this code

function for constructing a tree from inorder and preorder

struct treenode * construct(struct listnode *inptr,struct listnode * preptr ,int num)

{

struct treenode *temp;
struct listnode *q;
int i,j;
if(num==0)
return NULL;
temp=(struct treenode *)malloc(sizeof(struct treenode));
temp->info=preptr->info;
temp->left=NULL;
temp->right=NULL;
if(num==1)/*if only one node  in tree*/
return temp;
q=inptr;
for(i=q;q->info!=preptr->info;i++)
q=q->next;
/*now q points to root node in inorder list and the number of nodes in its left tree is i*/
/*for left subtree*/
temp->lchild=construct(inptr,preptr->next,i);
/*for right subtree*/
for(j=1;j<=i+1;j++)
preptr=preptr->next;
temp->rchild=construct(q->next,preptr,num-i-1);//unbale to understand this step as after node G construction value of i and num would be same this would result in -1
return temp;

}/*end of construct */

Steps for construction of tree from inorder and preorder traversals :frowning:geeksforgeekslink)

  1. Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick next element in next recursive call.

  2. Create a new tree node tNode with the data as picked element.

  3. Find the picked element’s index in Inorder. Let the index be inIndex.

  4. Call buildTree for elements before inIndex and make the built tree as left subtree of tNode.

  5. Call buildTree for elements after inIndex and make the built tree as right subtree of tNode.

  6. return tNode.

The basic problem with you is that you are not understanding recursion here ,
when there are 2 recursive calls in a function , then the first one is executed and second one goes to call stack and executed later when that call is popped .

hope that helps :slight_smile: