Write an efficient algorithm to construct a binary tree from the given inorder and postorder traversals.

For example,

Input:
 
Inorder Traversal   : { 4, 2, 1, 7, 5, 8, 3, 6 }
Postorder Traversal : { 4, 2, 7, 8, 5, 6, 3, 1 }
 
 
Output: Below binary tree

Difference between sum of nodes

Practice this problem

The idea is to start with the root node, which would be the last item in the postorder sequence, and find the boundary of its left and right subtree in the inorder sequence. To find the boundary, search for the index of the root node 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. Repeat this recursively for all nodes in the tree and construct the tree in the process.

 
To illustrate, consider the following inorder and postorder sequence:

Inorder   : { 4, 2, 1, 7, 5, 8, 3, 6 }
Postorder : { 4, 2, 7, 8, 5, 6, 3, 1 }

Root would be the last element in the postorder sequence, i.e., 1. Next, locate the index of the root node in the inorder sequence. Now since 1 is the root node, all nodes before 1 in the inorder sequence must be included in the left subtree of the root node, i.e., {4, 2} and all the nodes after 1 must be included in the right subtree, i.e., {7, 5, 8, 3, 6}. Now the problem is reduced to building the left and right subtrees and linking them to the root node.

Left subtree:
 
Inorder   : {4, 2}
Postorder : {4, 2}
 
Right subtree:
 
Inorder   : {7, 5, 8, 3, 6}
Postorder : {7, 8, 5, 6, 3}

The idea is to recursively follow the above approach until the complete tree is constructed. This is demonstrated below in C/C++, Java, and Python:

C


Download  Run Code

Output:

Inorder traversal is 4 2 1 7 5 8 3 6
Postorder traversal is 4 2 7 8 5 6 3 1

C++


Download  Run Code

Output:

Inorder traversal is 4 2 1 7 5 8 3 6
Postorder traversal is 4 2 7 8 5 6 3 1

Java


Download  Run Code

Output:

Inorder traversal is 4 2 1 7 5 8 3 6
Postorder traversal is 4 2 7 8 5 6 3 1

Python


Download  Run Code

Output:

Inorder traversal is 4 2 1 7 5 8 3 6
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 hashing and recursion. The time complexity of the C solution is O(n2) and requires O(n) extra space for the call stack.