Construct Binary Tree from Inorder and Postorder Traversal @LeetCode

PROBLEM :

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : (Recursive Solution)
--------------------------------------------------------------------------------

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        TreeNode* root ;
        int size=inorder.size() ;
        if(size==0)
            return NULL ;
       
        size-- ;
        root=BuiltPostOrderTree(inorder,postorder,0,size,&size) ;
        return root ;
    }
   
    TreeNode* BuiltPostOrderTree(vector<int> &inorder,vector<int> &postorder,int begin,int end,int *curr){
        if(begin>end)
            return NULL ;
 
        TreeNode* root=new TreeNode(postorder[(*curr)--]);
       
        if(begin==end)
            return root ;
       
        int index=FindIndex(inorder,root->val) ;
       
        root->right=BuiltPostOrderTree(inorder,postorder,index+1,end,&(*curr)) ;
        root->left=BuiltPostOrderTree(inorder,postorder,begin,index-1,&(*curr)) ;
       
        return root ;
    }
   
    int FindIndex(vector<int> &inorder,int data){
    for(int i=0;i<inorder.size();i++){
    if(inorder[i]==data)
    return i ;
}
}
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )