VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-all-possible-trees-with-given-inorder-traversal/

⇱ Find all possible Binary Trees with given Inorder Traversal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

Examples:

Input: inorder[] = {7, 5}
Output:
5 7
7 5

πŸ‘ example

Input: inorder[] = {1, 2, 3}
Output:
1 2 3
1 3 2
2 1 3
3 1 2
3 2 1

πŸ‘ example-1

Approach:

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.

Related articles:

Comment
Article Tags:
Article Tags: