Postorder traversal from given Inorder and Preorder traversals

PROBLEM :

Given a preOrder and inOrder traversal of a binary tree your task is to print the postOrder traversal of the tree .You are required to complete the function printPostOrder which prints the node of the tree in post order fashion . You should not read any input from stdin/console. There are multiple test cases. For each test case, this method will be called individually.

Example:

Input:
Inorder traversal in[] = {4, 2, 5, 1, 3, 6}
Preorder traversal pre[] = {1, 2, 4, 5, 3, 6}

Output:
Postorder traversal is {4, 5, 2, 6, 3, 1}
Trversals in the above example represents following tree

         1
      /     \  
     2       3
   /   \      \
  4     5      6
 

Input:
The task is to complete the function printPostOrder which takes 3 argument, the first being the array of inOrder Traversal of the tree (in) , the second beeing the preOrder traversal of the tree (pre) and third being the no of nodes of the Tree (N).
There are multiple test cases. For each test case, this method will be called individually.

Output:
The function should print the PostOrder traversal of the binary tree separated by space.


Constraints:
1 <=T<= 30
1 <=Number of nodes<= 100
1 <=Data of a node<= 1000

Example:

Input
1
6
4 2 5 1 3 6
1 2 4 5 3 6


Output
4  5  2  6  3 1

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

/*prints the post order traversal of the
tree */

int search(int [],int ,int ) ;

void printPostOrder(int in[], int pre[], int n)
{
    int pos ;
   
    pos=search(in,pre[0],n) ;
   
    if(pos!=0)
        printPostOrder(in,pre+1,pos) ;
    if(pos!=n-1)
        printPostOrder(in+pos+1,pre+pos+1,n-pos-1) ;
       
    cout<<pre[0]<<" " ;
   
}

int search(int in[],int ele,int n)
{
    int j ;
    for(j=0;j<n;j++)
    {
        if(in[j]==ele)
        return j ;
    }
}


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

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 )