

You are given ‘inOrder’ = {4, 2, 5, 1, 3, 6} and ‘levelOrder’ = {1, 2, 3, 4, 5, 6}. The binary tree constructed from given traversals will look like this:

The inorder traversal of the above tree will be { 4, 2, 5, 1, 3, 6 }.
The first line of the input contains a single integer 'T', representing the number of test cases.
The first line of each test case contains an integer 'N', which denotes the number of nodes in the tree.
The next line of each test case contains ‘N’ single space-separated integers, representing the in-order traversal of the Binary Tree.
The next line of each test case contains ‘N’ single space-separated integers, representing the level-order traversal of the Binary Tree.
For each test case, print the inorder traversal of the binary tree.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 2000
0 <= inOrder[i] <= 10^5
0 <= levelOrder[i] <= 10^5
Time Limit: 1 sec
Prerequisite: In-order and level-order traversal of a tree.
The basic is to find the root and recursively construct the left and right subtrees. The first element of the ‘LEVELORDER’ traversal will always be the root. We then find the position of the root in ‘INORDER’. As we know that in inorder traversal, we first travel the left child, then the root, and then the right child. So, we can say that the elements before the root in ‘INORDER’ will lie in the left subtree of the root, and elements after the root in the ‘INORDER’ will lie in the right subtree of the root.
In the same way, we will recursively create the left subtree and the right subtree.
Algorithm :
Maintain a function ‘BUILDTREEHELPER’(NODE, LEVELORDER, INORDER, INSTART, INEND);
In this approach, we will use a HashSet, ‘SET’ to reduce the time complexity from O(N ^ 3) to O(N ^ 2). The basic idea will be the same; we will find the root and recursively construct the left and right subtrees. The root will be the first element of ‘LEVELORDER’ and the elements before the root in ‘INORDER’ will lie in the left subtree of the root, and elements after the root in the ‘INORDER’ will lie in the right subtree of the root.
We will put the elements of the left subtree in the ‘SET’. Now, we will traverse the ‘LEVELORDER’ and if the current element of the ‘LEVELORDER’ is present in the ‘SET’ we will add it to ‘LEFTLEVEL’ otherwise we will add it to ‘RIGHTLEVEL’. We can check in constant time whether any element is present in ‘SET’ or not.
Now, we will use ‘LEFTLEVEL’ to create the left subtree and ‘RIGHTLEVEL’ to create the right subtree.
Algorithm :
Maintain a function ‘BUILDTREEHELPER’(‘LEVELORDER’, ‘INORDER’, ‘INSTART’, ‘INEND’, ‘N’).