Find all possible Binary Trees with given Inorder Traversal
Last Updated : 23 Jul, 2025
Given an array that represents Inorder Traversal, the task is to find all possible Binary Trees with the given inorder traversal and print their preorder traversals.
The idea is to generate all possible binary trees that can be formed from a given inorder traversal by recursively selecting each element as the root of the tree. Once a root is chosen, the remaining elements are divided into two subarraysβone for the left subtree and one for the right subtree. We then recursively generate all possible left and right subtrees for that root and combine them to form different binary trees.
Lets's say, for an inorder traversal [1, 2, 3]:
We treat each element (1, 2, or 3) as the root.
For root 2, the left subtree will be [1] and the right subtree will be [3]. Combine the trees formed from [1] and [3] with root 2 to generate one of the possible trees.
Repeat this for every element being the root and recursively generate subtrees.
Below is the implementation of the above approach:
Output
1 2 3
1 3 2
2 1 3
3 1 2
3 2 1
Time Complexity: O(n * Cnβ), where Cnβ is the Catalan number Auxiliary Space: O(Cnβ + n), for storing trees and the recursion stack.