Write an efficient algorithm to find postorder traversal on a given binary tree from its inorder and preorder sequence.

For example, consider the following tree:

Print Binary Tree

Input:
 
Inorder traversal is { 4, 2, 1, 7, 5, 8, 3, 6 }
Preorder traversal is { 1, 2, 4, 3, 5, 7, 8, 6 }
 
 
Output:
 
Postorder traversal is 4 2 7 8 5 6 3 1

Practice this problem

A simple solution would be to construct the binary tree from the given inorder and preorder sequences and then print the postorder traversal by traversing the tree.

 
We can avoid constructing the tree by passing some extra information in a recursive postorder call. In a simple recursive postorder call, the left subtree is processed first, followed by the right subtree, and finally, the node is printed. We can perform something similar for printing the postorder traversal.

The idea is to start with the root node, whose value would be the first item in the preorder sequence. We find boundaries of the left and right subtree of the current root node in the inorder sequence. To find the left and right subtree boundaries, search for the root node index in the inorder sequence. All keys before the root node in the inorder sequence become part of the left subtree, and all keys after the root node become part of the right subtree. If we repeat this recursively for all tree nodes, we will end up doing a postorder traversal on the tree. This algorithm is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Postorder traversal is 4 2 7 8 5 6 3 1

Java


Download  Run Code

Output:

Postorder traversal is 4 2 7 8 5 6 3 1

Python


Download  Run Code

Output:

Postorder traversal is 4 2 7 8 5 6 3 1

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(n) extra space for the hash table and call stack. Here‘s an implementation in C, which runs in O(n2) time.