Preorder from Inorder and Postorder traversals

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

Example:

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

Trversals in the above example represents following tree 
         1
      /    \       
     2       3
   /   \      \  
  4     5      6

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

We can print preorder 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 push right subtree to a stack, then left subtree and finally we push root. Finally we print contents of stack. To find boundaries of left and right subtrees in post[] 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 post[], 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.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print Postorder traversal from given
// Inorder and Preorder traversals.
import java.util.Stack;
  
public class PrintPre {
  
    static int postIndex;
  
    // Fills preorder traversal of tree with given
    // inorder and postorder traversals in a stack
    void fillPre(int[] in, int[] post, int inStrt,
                 int inEnd, Stack<Integer> s)
    {
        if (inStrt > inEnd)
            return;
  
        // Find index of next item in postorder traversal in
        // inorder.
        int val = post[postIndex];
        int inIndex = search(in, val);
        postIndex--;
  
        // traverse right tree
        fillPre(in, post, inIndex + 1, inEnd, s);
  
        // traverse left tree
        fillPre(in, post, inStrt, inIndex - 1, s);
  
        s.push(val);
    }
  
    // This function basically initializes postIndex
    // as last element index, then fills stack with
    // reverse preorder traversal using printPre
    void printPreMain(int[] in, int[] post)
    {
        int len = in.length;
        postIndex = len - 1;
        Stack<Integer> s = new Stack<Integer>();
        fillPre(in, post, 0, len - 1, s);
        while (s.empty() == false)
            System.out.print(s.pop() + " ");
    }
  
    // A utility function to search data in in[]
    int search(int[] in, int data)
    {
        int i = 0;
        for (i = 0; i < in.length; i++)
            if (in[i] == data)
                return i;
        return i;
    }
  
    // Driver code
    public static void main(String ars[])
    {
        int in[] = { 4, 10, 12, 15, 18, 22, 24, 25,
                     31, 35, 44, 50, 66, 70, 90 };
        int post[] = { 4, 12, 10, 18, 24, 22, 15, 31,
                       44, 35, 66, 90, 70, 50, 25 };
        PrintPre tree = new PrintPre();
        tree.printPreMain(in, post);
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to print Postorder traversal from given
// Inorder and Preorder traversals.
using System;
using System.Collections.Generic;
  
public class PrintPre 
{
  
    static int postIndex;
  
    // Fills preorder traversal of tree with given
    // inorder and postorder traversals in a stack
    void fillPre(int[] a, int[] post, int inStrt,
                int inEnd, Stack<int> s)
    {
        if (inStrt > inEnd)
            return;
  
        // Find index of next item in postorder traversal in
        // inorder.
        int val = post[postIndex];
        int inIndex = search(a, val);
        postIndex--;
  
        // traverse right tree
        fillPre(a, post, inIndex + 1, inEnd, s);
  
        // traverse left tree
        fillPre(a, post, inStrt, inIndex - 1, s);
  
        s.Push(val);
    }
  
    // This function basically initializes postIndex
    // as last element index, then fills stack with
    // reverse preorder traversal using printPre
    void printPreMain(int[] a, int[] post)
    {
        int len = a.Length;
        postIndex = len - 1;
        Stack<int> s = new Stack<int>();
        fillPre(a, post, 0, len - 1, s);
        while (s.Count!=0)
            Console.Write(s.Pop() + " ");
    }
  
    // A utility function to search data in in[]
    int search(int[] a, int data)
    {
        int i = 0;
        for (i = 0; i < a.Length; i++)
            if (a[i] == data)
                return i;
        return i;
    }
  
    // Driver code
    public static void Main(String []args)
    {
        int []a = { 4, 10, 12, 15, 18, 22, 24, 25,
                    31, 35, 44, 50, 66, 70, 90 };
        int []post = { 4, 12, 10, 18, 24, 22, 15, 31,
                    44, 35, 66, 90, 70, 50, 25 };
        PrintPre tree = new PrintPre();
        tree.printPreMain(a, post);
    }
}
  
// This code has been contributed by 29AjayKumar

chevron_right


Output:

25 15 10 4 12 22 18 24 50 35 31 44 70 66 90

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)

O(n) Solution

We can further optimize above solution to first hash all items of inorder traversal so that we do not have to linearly search items. With hash table available to us, we can search an item in O(1) time.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print Postorder traversal from given
// Inorder and Preorder traversals.
import java.util.Stack;
import java.util.HashMap;
  
public class PrintPre {
  
    static int postIndex;
  
    // Fills preorder traversal of tree with given
    // inorder and postorder traversals in a stack
    void fillPre(int[] in, int[] post, int inStrt, int inEnd,
                 Stack<Integer> s, HashMap<Integer, Integer> hm)
    {
        if (inStrt > inEnd)
            return;
  
        // Find index of next item in postorder traversal in
        // inorder.
        int val = post[postIndex];
        int inIndex = hm.get(val);
        postIndex--;
  
        // traverse right tree
        fillPre(in, post, inIndex + 1, inEnd, s, hm);
  
        // traverse left tree
        fillPre(in, post, inStrt, inIndex - 1, s, hm);
  
        s.push(val);
    }
  
    // This function basically initializes postIndex
    // as last element index, then fills stack with
    // reverse preorder traversal using printPre
    void printPreMain(int[] in, int[] post)
    {
        int len = in.length;
        postIndex = len - 1;
        Stack<Integer> s = new Stack<Integer>();
  
        // Insert values in a hash map and their indexes.
        HashMap<Integer, Integer> hm =
                     new HashMap<Integer, Integer>();
        for (int i = 0; i < in.length; i++)
            hm.put(in[i], i);
  
        // Fill preorder traversal in a stack
        fillPre(in, post, 0, len - 1, s, hm);
  
        // Print contents of stack
        while (s.empty() == false)
            System.out.print(s.pop() + " ");
    }
  
    // Driver code
    public static void main(String ars[])
    {
        int in[] = { 4, 10, 12, 15, 18, 22, 24, 25,
                     31, 35, 44, 50, 66, 70, 90 };
        int post[] = { 4, 12, 10, 18, 24, 22, 15, 31,
                       44, 35, 66, 90, 70, 50, 25 };
        PrintPre tree = new PrintPre();
        tree.printPreMain(in, post);
    }
}

chevron_right


Output:

25 15 10 4 12 22 18 24 50 35 31 44 70 66 90

Time Complexity: O(n)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : 29AjayKumar