Create a tree with (pre and inorder)

In this solution, I am using hash map to make it O(n)


for this test case it is giving wrong answer
1
8
4 8 2 5 1 6 3 7
8 4 5 2 6 7 3 1
correct answer is
1 2 4 8 5 3 6 7

approach is correct but you have done 2 mistakes

  1. make root node with c not with inorder[index]
  2. increase i before returning

and correct output for you given input is
Output
8 4 5 2 6 7 3 1
not 1 2 4 8 5 3 6 7

 int c = pre[i];

int index = mp[c];

i++;

node * root = new node(c);

after these changes it is giving correct output

MODIFIED CODE

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.