Form a Tree from Postorder and Inorder

PROBLEM :

Given inorder and postorder traversals of a Binary Tree, construct the tree

For example, if given inorder and postorder traversals are {4, 8, 2, 5, 1, 6, 3, 7} and {8, 4, 5, 2, 6, 7, 3, 1}  respectively, then your function should construct below tree.

          1
       /      \
     2        3
   /    \     /   \
  4     5   6    7
    \
      8

         

Input:
The task is to complete the method which takes three arguments, one is an array that has inorder traversal, second is another array that has postorder traversal, third is size of two arrays (You may assume that both arrays are of same size).

There are multiple test cases. For each test case, this method will be called individually.

Output:
The function should return root of constructed tree.

Constraints:
1 <=T<= 30
1 <= Size of arrays <= 100
1 <= Values in arrays <= 1000

Example:
Input:
1
8
4 8 2 5 1 6 3 7
8 4 5 2 6 7 3 1

Output :

         1
       /      \
     2        3
   /    \     /   \
  4     5   6    7
    \
      8

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/* Tree node structure
struct Node
{
   int data;
   struct Node *left, *right;
}*/

// Function should construct tree and return
// root of it.  in[] stores inorder traversal
// post[] stores postorder traversal.  n is
// size of these arrays


Node *create_tree(int [], int [], int ,int, int* ) ;

int search_position(int [],int ,int ,int ) ;

Node *buildTree(int in[], int post[], int n)
{
    if(n==0)
        return NULL ;
    n=n-1 ;
 
    Node *tree ;
    tree=create_tree(in,post,0,n,&n)  ;
 
    return tree ;
}

Node *create_tree(int in[], int post[], int start,int end,int *e)
{
    if(start>end)
        return NULL ;
 
 
    Node *temp ;
    temp=(Node*)malloc(sizeof(Node)) ;
    temp->data=post[(*e)--] ;
    temp->left=NULL ;
    temp->right=NULL ;
 
    if(start==end)
return temp ;

int inIndex ;
inIndex=search_position(in,start,end,temp->data) ;

temp->right=create_tree(in,post,inIndex+1,end,&(*e)) ;
temp->left=create_tree(in,post,start,inIndex-1,&(*e)) ;


return temp ;
}

int search_position(int in[],int start,int end,int data)
{
    int i ;
    for(i=start;i<end;i++)
    {
        if(in[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 )