Construct Tree from Inorder & Preorder | Practice | GeeksforGeeks

Given 2 Arrays of Inorder and preorder traversal. Construct a tree and print the Postorder traversal. 
Example 1:
Input:
N = 4
inorder[] = {1 6 8 7}
preorder[] = {1 6 7 8}
Output: 8 7 6 1

Example 2:
Input:
N = 6
inorder[] = {3 1 4 0 5 2}
preorder[] = {0 1 3 4 2 5}
Output: 3 4 1 5 2 0
Explanation: The tree will look like
       0
    /     \
   1       2
 /   \    /
3    4   5
Your Task:
Your task is to complete the function buildTree() which takes 3 arguments(inorder traversal array, preorder traversal array, and size of tree n) and returns the root node to the tree constructed. You are not required to print anything and a new line is added automatically (The post order of the returned tree is printed by the driver's code.)
Expected Time Complexity: O(N*N).
Expected Auxiliary Space: O(N).
Constraints:
1<=Number of Nodes<=1000
0
ruchitchudasama1236 hours ago
class Solution{
    public:
    Node* makeBT(int in[],int pre[],int li,int hi,int lp,int hp,map<int,int> &mpp){
        if(lp<0 || lp>hp)return NULL;
    
        int rootData=pre[lp];
        Node* root=new Node(rootData);
        int index = mpp[rootData];
        int numLeft=lp+index-li;
        root->left=makeBT(in,pre,li,index-1,lp+1,numLeft,mpp);
        root->right=makeBT(in,pre,index+1,hi,numLeft+1,hp,mpp);
        return root;
    
    }
    Node* buildTree(int in[],int pre[], int n)
    {
        map<int,int> mpp;
        for(int i=0;i<n;i++){
            mpp[in[i]]=i;
        }
        return makeBT(in,pre,0,n-1,0,n-1,mpp);
    }
};
0
utkarshagarwal1011 day ago
class Solution{
    public:
        
    Node* helper(int prestart, int preend, int instart, int inend, int preorder[], int inorder[],int n){
        if(prestart>preend||instart>inend){
            return NULL;
        }
        Node* curr = new Node(preorder[prestart]);
        
        int idx=instart;
        int leftTreeSize =0;
        while(idx<n&&inorder[idx]!=preorder[prestart]){
            idx++;
            leftTreeSize++;
        }
        Node* leftTree = helper(prestart+1,prestart+leftTreeSize,instart,idx-1,preorder,inorder,n);
        Node* rightTree = helper(prestart+leftTreeSize+1,preend,idx+1,inend,preorder,inorder,n);
        curr->left = leftTree;
        curr->right = rightTree;
        return curr;
           
    }
    Node* buildTree(int in[],int pre[], int n)
    {
        // Code here
        return helper(0,n-1,0,n-1,pre,in,n);
    }
};
0
mirsayib1 day ago
class Solution{
    public:
    unordered_map<int, int> ump;
    Node* helper(int* inorder, int* preorder, int st, int en, int pr_st){
        
        if(st > en) return NULL;
        
        int root_val = preorder[pr_st];
        int root_idx = ump[root_val]; //index of root in inorder arr
        
        int l_size = root_idx-st;
        
        Node* root = new Node(root_val);
        
        
        root->left = helper(inorder, preorder, st, root_idx-1, pr_st+1);
        root->right = helper(inorder, preorder, root_idx+1, en, pr_st+l_size+1);
        
        return root;
        
        
    }
    Node* buildTree(int inorder[],int preorder[], int n)
    {
        // Code here
        for(int i = 0; i<n; i++) ump[inorder[i]] = i;
        
        return helper(inorder, preorder, 0, n-1, 0);
        
        
    }
};
0
akashdogra1712 days ago
Node* helper(int in[], int pre[], int inS, int inE, int preS, int preE){       if(inS > inE){           return NULL;       }              int rootData = pre[preS];       int rootIndex = -1;       for(int i =inS;i<=inE;i++){           if(in[i] == rootData){               rootIndex = i;               break;           }       }                       int leftInS = inS;       int leftInE = rootIndex - 1;       int leftPreS = preS + 1;       int leftPreE = leftPreS + leftInE - leftInS;              int rightInS = rootIndex + 1;       int rightInE = inE;       int rightPreS = leftPreE + 1;       int rightPreE = preE;                     Node* root = new Node(rootData);       root->left = helper(in,pre, leftInS, leftInE, leftPreS, leftPreE);       root->right = helper(in, pre, rightInS, rightInE, rightPreS, rightPreE);   }      Node* buildTree(int in[],int pre[], int n)   {       helper(in, pre , 0, n-1 , 0 , n-1);   }
 
+1
parasdhanwal263 days ago
<<Java Solution>>
 
class Solution
{
    public static Node buildTree(int inorder[], int preorder[], int n)
    {
        HashMap<Integer,Integer> map=new HashMap<>();
        
        for(int i=0;i<inorder.length;i++)
        {
            map.put(inorder[i],i);
        }
        
        Node ans=construct(preorder,0,n-1,inorder,0,n-1,map);
        return ans;
        // code here 
    }
    
    static Node construct(int preorder[], int prestart, int preend, int inorder[], int instart, int inend,
            HashMap<Integer, Integer> map) {
        if(prestart>preend||instart>inend)
        {
            return null;
            
        }
        
        Node newNode=new Node(preorder[prestart]);
        int rootlocationinorder=map.get(preorder[prestart]);
        int no_of_children=rootlocationinorder-instart;
        newNode.left=construct(preorder,prestart+1,prestart+1+no_of_children,inorder,instart,rootlocationinorder-1,map);
        newNode.right=construct(preorder,prestart+1+no_of_children,preend,inorder,rootlocationinorder+1,inend,map);
        
        return newNode;
    }
}

0
ialtafshaikh1 week ago
Easy and optimised solution in Python-------------------------------------
def buildtree(self, inorder, preorder, n):
        inorderMap = { inorder[index] : index for index in range(len(inorder))}
        return self.treeConstruction(preorder, inorderMap, 0, n-1)
        
    def treeConstruction(self, preorder, inorderMap, start, end):
        if(start > end or not len(preorder)): return None
        root = Node(preorder.pop(0))
        
        root.left = self.treeConstruction(preorder,inorderMap, start, inorderMap[root.data] - 1)
        root.right = self.treeConstruction(preorder,inorderMap, inorderMap[root.data] + 1, end)
        
        return root
0
mayankkannojia291 week ago
So nodes data are distinct nos?
+2
6288262 weeks ago
Nice and concise.
The while-loop might be a little noisy, but the code is decent.
if (n == 0)
	return NULL;
	
Node *node = new Node(pre[0]);
int i = 0;

while (in[i] != pre[0])
	++ i;
	
node->left = buildTree(in, pre + 1, i ++);
node->right = buildTree(in + i, pre + i, n - i);

return node;
0
koulikmaity3 weeks ago
int findPosition(int in[], int element, int n)   {       for(int i=0; i<n; i++)       {           if(in[i] == element)               return i;       }       return -1;   }      Node* solve(int in[], int pre[], int &index, int inorderStart, int inorderEnd, int n)   {       // base case       if(index >= n || inorderStart>inorderEnd)           return NULL;              int element = pre[index++];       int position = findPosition(in, element, n);       Node* root = new Node(element);                     // recursive call for left       root->left = solve(in, pre, index, inorderStart, position-1, n);       root->right = solve(in, pre, index, position+1, inorderEnd, n);              return root;          }      Node* buildTree(int in[],int pre[], int n)   {       int preOrderIndex = 0;       Node* ans = solve(in, pre, preOrderIndex, 0, n-1, n );       return ans;          }
+1
smdakhtar0073 weeks ago
class Solution{
    public:
    int search(int arr[]  , int st , int en , int data)
    {
        for(int i = st ; i<=en ; i++){
            if((arr[i])==data){
                return i;
            }
        }
    }
     int preindex = 0 ;
    Node*traversal(int in[] , int pre[] , int st , int end){
        
        if(st>end){
            return NULL;
        }
        Node*ans = new Node(pre[preindex++]);
        if(st==end){
            return ans;
        }
        int inindex = search(in ,st , end , ans->data);
        ans->left=traversal(in,pre,st,inindex-1);
        ans->right=traversal(in ,pre, inindex+1,end);
        return ans;
        
    }
    Node* buildTree(int in[],int pre[], int n)
    {
       return traversal(in , pre  , 0 , n-1);
    }
    
    
};
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.