Given an inorder sequence of a binary tree, find all possible binary trees having that same inorder traversal.

For example, there are 5 binary trees with inorder traversal [1, 2, 3], as shown below:

  1          1          2          3          3
   \          \        / \        /          /
    2          3      1   3      1          2
     \        /                   \        /
      3      2                     2      1

Practice this problem

We know that, in the inorder traversal on a given binary tree, all nodes in the left subtree of the root must appear before the root node and all nodes in the right subtree appear after the root node. Therefore, for inorder sequence in[0, n-1] with i'th element as root, all elements in range in[0, i-1] will be part of the left subtree, and all elements in range in[i+1, n-1] will be part of the right subtree.

 
The idea is to iterate over the given inorder sequence and consider each element as the root of the binary tree. Then recursively construct all possible left and right subtrees of the root. Finally, create a tree for each pair of left and right subtree, and add that tree to the output list.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Total binary trees are 5
 
Preorder traversal for each tree:
1 2 3
1 3 2
2 1 3
3 1 2
3 2 1