 # Can't Figure out my mistake in this recursive solution

#1
```````

TreeNode* solve(vector<int> &A, vector<int> &B, int lo, int hi)
{
if(lo>hi) return NULL;
TreeNode* ret = new TreeNode(A[lo]);
int ind;
for(int i=lo;i<=hi;i++)
{
if(A[lo]==B[i])
{
ind=i;
break;
}
}
int num = ind-lo;
ret->left = solve(A,B,lo+1,lo+num);
ret->right = solve(A,B,lo+num+1,hi);
return ret;
}
TreeNode* Solution::buildTree(vector<int> &A, vector<int> &B) {
TreeNode* ret;
int n= A.size();
ret = solve(A,B,0,n-1);
queue <TreeNode*> q;
q.push(ret);
while(!q.empty())
{
TreeNode* top = q.front();
q.pop();
if(top==NULL) continue;
cout<<top->val<<" ";
q.push(top->left);
q.push(top->right);
}
return ret;
}
`
Input:
preorder 1 2 3 4 5
inorder: 3 2 4 1 5

Output:
BFS: 1 2 5 3 4 -1 -1 -1 -1 -1 -1
preorder: 1 2 3 4 5
post order: 4 3 2 5 1``````

#2

lo and hi aren’t the same for both A and B, except in the initial recursive call from buildTree() function.
For example, consider A = [1,2,3] and B = [2,1,3]. Here 1 is the root, therefore, while partitioning, for left subtree, we require  from A and B, which are given by the range [1 1] for A and [0 0] for B. Now in your code, as you are passing only [lo+1 lo+num] for left subtree, only [1 1] gets passed which corresponds only to A and not to B.
Hence maintain another set of lo and hi for B, calculate them accordingly and pass them as well.