Construct Tree from Preorder Traversal
Submissions: 3583   Accuracy:

58.44%

  Difficulty: Medium   Marks: 4

Given an array pre[] that represents Preorder traversal of a binary tree. One more array preLN[] is given which has only two possible values ‘L’ and ‘N’. The value ‘L’ in preLN[] indicates that the corresponding node in Binary Tree is a leaf node and value ‘N’ indicates that the corresponding node is non-leaf node.

Input:
There will be T, test cases and for each test case the function will be called separately.
The function takes three arguments as input, first an integer N, denoting the size of both the array, second an array pre[] that represents Preorder traversal of the binary tree and the last argument a character array preLN[] which indicates that the corresponding node in Binary Tree is a leaf node or a normal node.

Output:
The output will be the inorder traversal of the resultant tree.

Constraints:
1 <=T <= 75
1 <= N <= 100
1 <= pre[i] <= 100
preLN[i]: {'N', 'L'}

User Task:
Your task is to complete the function constructTree(), that constructs the tree from the given two arrays and return the root pointer to new binary tree formed.

Example:
Input:

3
5
10 30 20 5 15 
N N L L L 
4
1 2 4 3 
N N L L 
6
1 2 4 6 5 3 
N N N L L L

Output:
20 30 5 10 15 
4 2 3 1 
6 4 5 2 3 1 

Explanation:
Testcase 1:
Binary tree for the given pre array is:

The inorder traversal of given binary tree is: 20 30 5 10 15.

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

Contributor: Harshit Sidhwa
Author: harshitsidhwa


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.