Tree from Postorder and Inorder
Submissions: 9294   Accuracy:

46.51%

  Difficulty: Medium   Marks: 4

Given inorder and postorder traversals of a Binary Tree in the arrays in[] and post[] respectively. The task is to construct the binary tree from these traversals.

For example, if given inorder and postorder traversals are {4, 8, 2, 5, 1, 6, 3, 7} and {8, 4, 5, 2, 6, 7, 3, 1}  respectively, then your function should construct below tree.

          1
       /      \
     2        3
   /    \     /   \
  4     5   6    7
    \
      8

Input Format:
First line of input contains number of testcases T. For each testcase, first line of input contains number of nodes in the tree, and next two lines contains inorder and postorder respectively.

Output Format:
For each testcase, print the preorder traversal of tree.

Your Task:
Complete the function buildTree() which inorder, postorder and number of nodes in the tree, and returns the root of the tree.

Constraints:
1 <= T <= 30
1 <= N <= 103
1 <= in[i], post[i] <= 103

Example:
Input:

2
8
4 8 2 5 1 6 3 7
8 4 5 2 6 7 3 1
5
9 3 2 5 4
5 9 3 4 2

Output:
1 2 4 8 5 3 6 7
2 9 5 4 3

Explanation:
Testcase 1:

          1
       /      \
     2        3
   /    \     /   \
  4     5   6    7
    \
      8

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Amit Khandelwal
Author: kartik


If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.


to report an issue on this page.