# Print Postorder traversal from given Inorder and Preorder traversals

Given Inorder and Preorder traversals of a binary tree, print Postorder traversal.

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

A naive method is to first construct the tree, then use simple recursive method to print postorder traversal of the constructed tree.

We can print postorder traversal without constructing the tree. The idea is, root is always the first item in preorder traversal and it must be the last item in postorder traversal. We first recursively print left subtree, then recursively print right subtree. Finally, print root. To find boundaries of left and right subtrees in pre[] and in[], we search root in in[], all elements before root in in[] are elements of left subtree and all elements after root are elements of right subtree. In pre[], all elements after index of root in in[] are elements of right subtree. And elements before index (including the element at index and excluding the first element) are elements of left subtree.

## C++

 // C++ program to print postorder traversal from preorder and inorder traversals #include using namespace std;    // A utility function to search x in arr[] of size n int search(int arr[], int x, int n) {     for (int i = 0; i < n; i++)         if (arr[i] == x)             return i;     return -1; }    // Prints postorder traversal from given inorder and preorder traversals void printPostOrder(int in[], int pre[], int n) {     // The first element in pre[] is always root, search it     // in in[] to find left and right subtrees     int root = search(in, pre[0], n);        // If left subtree is not empty, print left subtree     if (root != 0)         printPostOrder(in, pre + 1, root);        // If right subtree is not empty, print right subtree     if (root != n - 1)         printPostOrder(in + root + 1, pre + root + 1, n - root - 1);        // Print root     cout << pre[0] << " "; }    // Driver program to test above functions int main() {     int in[] = { 4, 2, 5, 1, 3, 6 };     int pre[] = { 1, 2, 4, 5, 3, 6 };     int n = sizeof(in) / sizeof(in[0]);     cout << "Postorder traversal " << endl;     printPostOrder(in, pre, n);     return 0; }

## Java

 // Java program to print postorder  // traversal from preorder and // inorder traversals import java.util.Arrays;    class GFG {    // A utility function to search x in arr[] of size n static int search(int arr[], int x, int n) {     for (int i = 0; i < n; i++)         if (arr[i] == x)             return i;     return -1; }    // Prints postorder traversal from  // given inorder and preorder traversals static void printPostOrder(int in1[],                     int pre[], int n) {     // The first element in pre[] is      // always root, search it in in[]      // to find left and right subtrees     int root = search(in1, pre[0], n);        // If left subtree is not empty,     // print left subtree     if (root != 0)         printPostOrder(in1, Arrays.copyOfRange(pre, 1, n), root);        // If right subtree is not empty,     // print right subtree     if (root != n - 1)         printPostOrder(Arrays.copyOfRange(in1, root+1, n),             Arrays.copyOfRange(pre, 1+root, n), n - root - 1);        // Print root     System.out.print( pre[0] + " "); }    // Driver code public static void main(String args[]) {     int in1[] = { 4, 2, 5, 1, 3, 6 };     int pre[] = { 1, 2, 4, 5, 3, 6 };     int n = in1.length;     System.out.println("Postorder traversal " );     printPostOrder(in1, pre, n); } } // This code is contributed by Arnab Kundu

## Python3

 # Python program to print postorder  # traversal from preorder and  # inorder traversals def printpostorder(inorder, preorder, n):     if preorder[0] in inorder:         root = inorder.index(preorder[0])                if root != 0: # left subtree exists         printpostorder(inorder[:root],                         preorder[1:root + 1],                         len(inorder[:root]))            if root != n - 1: # right subtree exists         printpostorder(inorder[root + 1:],                          preorder[root + 1:],                         len(inorder[root + 1:]))            print preorder[0],            # Driver Code inorder = [4, 2, 5, 1, 3, 6]; preorder = [1, 2, 4, 5, 3, 6]; n = len(inorder) print "Postorder traversal " printpostorder(inorder, preorder, n)    # This code is contributed by SaiNath

Output:

Postorder traversal
4 5 2 6 3 1

Below is the implementation.

## Java

 // Java program to print Postorder traversal from given Inorder // and Preorder traversals.    public class PrintPost {     static int preIndex = 0;     void printPost(int[] in, int[] pre, int inStrt, int inEnd)     {         if (inStrt > inEnd)              return;                    // Find index of next item in preorder traversal in         // inorder.         int inIndex = search(in, inStrt, inEnd, pre[preIndex++]);            // traverse left tree         printPost(in, pre, inStrt, inIndex - 1);            // traverse right tree         printPost(in, pre, inIndex + 1, inEnd);            // print root node at the end of traversal         System.out.print(in[inIndex] + " ");     }        int search(int[] in, int startIn, int endIn, int data)     {         int i = 0;         for (i = startIn; i < endIn; i++)              if (in[i] == data)                  return i;                     return i;     }        // Driver code     public static void main(String ars[])     {         int in[] = { 4, 2, 5, 1, 3, 6 };         int pre[] = { 1, 2, 4, 5, 3, 6 };         int len = in.length;         PrintPost tree = new PrintPost();         tree.printPost(in, pre, 0, len - 1);     } }

## C#

 // C# program to print Postorder  // traversal from given Inorder  // and Preorder traversals.  using System;    class GFG { public static int preIndex = 0; public virtual void printPost(int[] arr, int[] pre,                                int inStrt, int inEnd) {     if (inStrt > inEnd)     {         return;     }        // Find index of next item in preorder     // traversal in inorder.      int inIndex = search(arr, inStrt, inEnd,                           pre[preIndex++]);        // traverse left tree      printPost(arr, pre, inStrt, inIndex - 1);        // traverse right tree      printPost(arr, pre, inIndex + 1, inEnd);        // print root node at the end of traversal      Console.Write(arr[inIndex] + " "); }    public virtual int search(int[] arr, int startIn,                           int endIn, int data) {     int i = 0;     for (i = startIn; i < endIn; i++)     {         if (arr[i] == data)         {             return i;         }     }     return i; }    // Driver code  public static void Main(string[] ars) {     int[] arr = new int[] {4, 2, 5, 1, 3, 6};     int[] pre = new int[] {1, 2, 4, 5, 3, 6};     int len = arr.Length;     GFG tree = new GFG();     tree.printPost(arr, pre, 0, len - 1); } }    // This code is contributed by Shrikant13

Output:

4 5 2 6 3 1

Time Complexity: The above function visits every node in array. For every visit, it calls search which takes O(n) time. Therefore, overall time complexity of the function is O(n2)

The above solution can be optimized using hashing. We use a HashMap to store elements and their indexes so that we can quickly find index of an element.

## Java

 // Java program to print Postorder traversal from  // given Inorder and Preorder traversals.  import java.util.*;    public class PrintPost {      static int preIndex = 0;      void printPost(int[] in, int[] pre, int inStrt,                int inEnd, HashMap hm)      {          if (inStrt > inEnd)              return;                     // Find index of next item in preorder traversal in          // inorder.          int inIndex = hm.get(pre[preIndex++]);             // traverse left tree          printPost(in, pre, inStrt, inIndex - 1, hm);             // traverse right tree          printPost(in, pre, inIndex + 1, inEnd, hm);             // print root node at the end of traversal          System.out.print(in[inIndex] + " ");      }         void printPostMain(int[] in, int[] pre)      {         int n = pre.length;         HashMap hm = new HashMap();         for (int i=0; i

## C#

 // C# program to print Postorder  // traversal from given Inorder  // and Preorder traversals.  using System;    class GFG { public static int preIndex = 0; public virtual void printPost(int[] arr, int[] pre,                                int inStrt, int inEnd) {     if (inStrt > inEnd)     {         return;     }        // Find index of next item in preorder     // traversal in inorder.      int inIndex = search(arr, inStrt, inEnd,                           pre[preIndex++]);        // traverse left tree      printPost(arr, pre, inStrt, inIndex - 1);        // traverse right tree      printPost(arr, pre, inIndex + 1, inEnd);        // print root node at the     // end of traversal      Console.Write(arr[inIndex] + " "); }    public virtual int search(int[] arr, int startIn,                           int endIn, int data) {     int i = 0;     for (i = startIn; i < endIn; i++)     {         if (arr[i] == data)         {             return i;         }     }     return i; }    // Driver code  public static void Main(string[] ars) {     int[] arr = new int[] {4, 2, 5, 1, 3, 6};     int[] pre = new int[] {1, 2, 4, 5, 3, 6};     int len = arr.Length;     GFG tree = new GFG();     tree.printPost(arr, pre, 0, len - 1); } }    // This code is contributed by Shrikant13

Output:

4 5 2 6 3 1

Time complexity: O(n)

## tags:

Tree Java-HashMap Payu Payu Tree