Leaderboard
Showing:
Handle Score
@Ibrahim Nash 5725
@blackshadows 5685
@akhayrutdinov 5111
@mb1973 4989
@Quandray 4908
@saiujwal13083 4156
@sanjay05 3762
@marius_valentin_dragoi 3511
@sushant_a 3453
@KshamaGupta 3318
@the_coder95 3302
Complete Leaderboard
Construct Tree from Preorder Traversal
Medium Accuracy: 50.68% Submissions: 10180 Points: 4

Construct a binary tree of size N using 2 given arrays pre[] and preLN[]. Array pre[] represents preorder traversal of a binary tree. Array preLN[] 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 a non-leaf node.
Note: Every node in the binary tree has either 0 or 2 children.

Example 1:

Input :      
N = 5
pre[] = {10, 30, 20, 5, 15}
preLN[] = {N, N, L, L, L}

Output:
          10
        /    \
      30      15
     /  \     
   20    5   

 

Your Task:  
You dont need to read input or print anything. Complete the function constructTree() which takes N, pre[] and preLN[] as input parameters and returns the root node of the constructed binary tree.

Note: The output generated by the compiler will contain the inorder traversal of the created binary tree.
 

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)


Constraints:
1 ≤ N ≤ 104
1 ≤ pre[i] ≤ 107
preLN[i]: {'N', 'L'}

to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

Construct Tree from Preorder Traversal

Output Window