Techie Delight
Coding made easy


Write an efficient algorithm to construct a binary tree from given inorder and level-order sequence.

For example,
Input: 

Inorder Traversal     : { 4, 2, 5, 1, 6, 3, 7 }
Level-order Traversal : { 1, 2, 3, 4, 5, 6, 7 }


Output: Below binary tree

Binary Tree

The idea is to start with the root node which would be the node with minimum index in level-order sequence and partition the inorder sequence for left and right subtree. To find the boundary of left and right subtree, search for index of the root node in inorder sequence. Then all keys before the root node in inorder sequence becomes part of the left subtree and all keys after the root node becomes part of the right subtree. We repeat this recursively for all nodes in the tree, and construct the tree in the process.

To illustrate, consider below inorder and level-order sequence –
    Inorder     : { 4, 2, 5, 1, 6, 3, 7 }
Level-order : { 1, 2, 3, 4, 5, 6, 7 }

Root node is present at first index in the level-order sequence i.e. node 1 is the root node. Now since node 1 is the root, all nodes before node 1 i.e. {4, 2, 5} in the inorder sequence must be included in the left subtree of the root node and all the nodes after node 1 i.e. {6, 3, 7} must be included in the right subtree. This reduces the problem into building the left and right subtrees and linking them to the root node.
Left subtree:

Inorder     : { 4, 2, 5 }
Level-order : { 1, 2, 3, 4, 5, 6, 7 }

Right subtree:

    Inorder     : { 6, 3, 7 }
Level-order : { 1, 2, 3, 4, 5, 6, 7 }

In the respective inorder sequence, the key which appears first in the level-order traversal becomes the root node for the corresponding left or right subtree. This is demonstrated below in C++, Java and Python:

C++

Download   Run Code

Output:

Inorder traversal of the constructed tree: 4 2 5 1 6 3 7

Java

Download   Run Code

Output:

Inorder traversal of the constructed tree: 4 2 5 1 6 3 7

Python

Download   Run Code

Output:

Inorder traversal of the constructed tree: 4 2 5 1 6 3 7

Download   Run Code
Output:

Inorder traversal of the constructed tree: 4 2 5 1 6 3 7

Download   Run Code
Output:

Inorder traversal of the constructed tree: 4 2 5 1 6 3 7

Download   Run Code
Output:

Inorder traversal of the constructed tree: 4 2 5 1 6 3 7

The time complexity of above solution is O(n2) and requires O(n) extra space for map and recursive call stack.

source