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;
return NULL;
temp=(struct treenode *)malloc(sizeof(struct treenode));
if(num==1)/*if only one node  in tree*/
return temp;
/*now q points to root node in inorder list and the number of nodes in its left tree is i*/
/*for left subtree*/
/*for right subtree*/
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: