Construct Tree from Preorder Traversal | Practice | GeeksforGeeks

Construct a binary tree of size N using two 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'}
0
ialtafshaikh1 day ago
Python Solution | Recursive with Map | Easy -----------
 
def constructTree(pre, preLN, n):
    if(n < 1 or not len(pre)): return 
    
    leafNodeMap = { pre[index] : preLN[index] for index in range(len(preLN))}
    
    return treeConstruction(pre, leafNodeMap)
        
def treeConstruction(pre, leafNodeMap):
    if(len(pre)):
        root = Node(pre.pop(0))
        
        if(leafNodeMap[root.data] == "N"):
            # if it is a node then attach child nodes
            root.left = treeConstruction(pre, leafNodeMap)
            root.right = treeConstruction(pre, leafNodeMap)
        return root
    return 

+1
wolfofsv4 days ago
struct Node *constructTree(int n, int pre[], char preLN[])
{
    // Code here
    stack<Node*>st;
    Node* root = new Node(pre[0]);
    if(preLN[0] == 'N'){
        st.push(root);
    }
    int i = 1;
    while(!st.empty()){
        Node* child = new Node(pre[i]);
        Node* par = st.top();
        if(par -> left == NULL){
            par -> left = child;
        }
        else{
            par -> right = child;
            st.pop();
        }
        if(preLN[i] == 'N'){
            st.push(child);
        }
        i++;
    }
    return root;
}
0
sethiyashristi202 weeks ago
struct Node *helper(int n,int pre[],char preLN[],int &i){      int val=pre[i];   struct Node* newnode=new struct Node(val);   if(preLN[i]!='L')   {       i++;       newnode->left=helper(n,pre,preLN,i);       newnode->right=helper(n,pre,preLN,i);   }   else i++;   return newnode;}struct Node *constructTree(int n, int pre[], char preLN[]){   // Code here   int i=0;  return helper(n,pre,preLN,i);  }
+1
detroix071 month ago
Node* solve(int n,int pre[],char preLN[],int &PreStartIndex){  // base case 
  if(PreStartIndex >= n) {    return NULL;  }    // create a root node     Node* root = new Node (pre[PreStartIndex]);  if(preLN[PreStartIndex]=='N') {    PreStartIndex+=1;    root->left=solve(n,pre,preLN,PreStartIndex);    root->right=solve(n,pre,preLN,PreStartIndex);  } else {    PreStartIndex+=1;    return root;  }}
struct Node *constructTree(int n, int pre[], char preLN[]){    int PreStartIndex = 0;    Node* ans = solve(n,pre,preLN,PreStartIndex);    return ans;}
0
golaravi5552 months ago
void tree(Node* &root,int &i, int pre[],char preLN[]){   if(preLN[i]=='L'){       root=new Node(pre[i]);       return;   }   else{       root=new Node(pre[i]);       i++;       tree(root->left,i,pre,preLN);       i++;       tree(root->right,i,pre,preLN);       return;   }       }struct Node *constructTree(int n, int pre[], char preLN[]){   // Code here   Node* root=NULL;   int i=0;  tree(root,i,pre,preLN);  return root;       }
+2
mohankumarit20012 months ago
ITERATIVE SOLUTION || O(N) || 0.2 ms
struct Node *constructTree(int n, int pre[], char preLN[])
{
    Node *root = new Node(pre[0]);
    stack<Node*> stk;int index=1;
    stk.push(root);
    while(!stk.empty() && index<n){
        Node *node = stk.top();
        if(!node->left){
            node->left = new Node(pre[index]);
            stk.push(node->left);
        }
        else if(!node->right){
            node->right = new Node(pre[index]);
            stk.push(node->right);
        }
        else {stk.pop();continue;}
        if(preLN[index]=='L'){
            stk.pop();
        }
        index++;
    }
    return root;
}
0
maheshahirwar2042 months ago
JAVA SOLUTION 
 
class Solution{   int i=0;   Node constructTree(int n, int pre[], char preLN[]){ if(i==n)return null;  Node root=new Node(pre[i]); if(preLN[i++]=='L'){     root.left=root.right=null;     return root; } root.left=constructTree(n,pre,preLN); root.right=constructTree(n,pre,preLN); return root;   }
}
0
hamidnourashraf2 months ago
def rec_build_tree(pre, preLN, idx):
    if idx == len(pre):
        return None, idx
    root = Node(pre[idx])
    root_type = preLN[idx]
    idx += 1
    if root_type == 'N':
        root.left, idx = rec_build_tree(pre, preLN, idx)
        root.right, idx = rec_build_tree(pre, preLN, idx)
    return root, idx
    
def constructTree(pre, preLN, n):
    idx = 0
    root, _ = rec_build_tree(pre, preLN, idx)
    return root
0
shreyash9779663 months ago
CPP SOLUTION

Node * construct(int pre[],char preLN[],int n,int &i)
{
if(i>=n)return NULL;
      Node *root=new Node(pre[i]);
      if(preLN[i]=='N')
      {
          i++;
          root->left=construct(pre,preLN,n,i);
          i++;
          root->right=construct(pre,preLN,n,i);
      }
      return root;
}

struct Node *constructTree(int n, int pre[], char preLN[])
{
    // Code here
    int i=0;
    return construct(pre,preLN,n,i);
    
}
-1
amannamdev28093 months ago
Easy way recursive solution:
Node* solve(int pre[],char preLN[],int n,int& i){    if(i>=n)   return NULL;   if(preLN[i]=='N')   {       Node *temp=new Node(pre[i]);       i++;       temp->left=solve(pre,preLN,n,i);       temp->right=solve(pre,preLN,n,i);       return temp;   }   Node *temp=new Node(pre[i]);   i++;   return temp;}
struct Node *constructTree(int n, int pre[], char preLN[]){ int i=0;   return solve(pre,preLN,n,i);}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.