Open In App

Find all possible binary trees with given Inorder Traversal

Last Updated : 25 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array that represents Inorder Traversal, find all possible Binary Trees with the given Inorder traversal and print their preorder traversals.
Examples: 
 

Input:   in[] = {3, 2};
Output:  Preorder traversals of different possible Binary Trees are:
         3 2
         2 3
Below are different possible binary trees
    3        2
     \      /
      2    3

Input:   in[] = {4, 5, 7};
Output:  Preorder traversals of different possible Binary Trees are:
          4 5 7 
          4 7 5 
          5 4 7 
          7 4 5 
          7 5 4 
Below are different possible binary trees
  4         4           5         7       7
   \          \       /   \      /       /
    5          7     4     7    4       5
     \        /                  \     /
      7      5                    5   4 

We strongly recommend you to minimize your browser and try this yourself first.
Let given inorder traversal be in[]. In the given traversal, all nodes in left subtree of in[i] must appear before it and in right subtree must appear after it. So when we consider in[i] as root, all elements from in[0] to in[i-1] will be in left subtree and in[i+1] to n-1 will be in right subtree. If in[0] to in[i-1] can form x different trees and in[i+1] to in[n-1] can from y different trees then we will have x*y total trees when in[i] as root. So we simply iterate from 0 to n-1 for root. For every node in[i], recursively find different left and right subtrees. If we take a closer look, we can notice that the count is basically n’th Catalan number. We have discussed different approaches to find n’th Catalan number here.
The idea is to maintain a list of roots of all Binary Trees. Recursively construct all possible left and right subtrees. Create a tree for every pair of left and right subtree and add the tree to list. Below is detailed algorithm. 
 

1) Initialize list of Binary Trees as empty.  
2) For every element in[i] where i varies from 0 to n-1,
    do following
......a)  Create a new node with key as 'arr[i]', 
          let this node be 'node'
......b)  Recursively construct list of all left subtrees.
......c)  Recursively construct list of all right subtrees.
3) Iterate for all left subtrees
   a) For current leftsubtree, iterate for all right subtrees
        Add current left and right subtrees to 'node' and add
        'node' to list.

 

C++




// C++ program to find binary tree with given inorder
// traversal
#include <bits/stdc++.h>
using namespace std;
 
// Node structure
struct Node
{
    int key;
    struct Node *left, *right;
};
 
// A utility function to create a new tree Node
struct Node *newNode(int item)
{
    struct Node *temp = new Node;
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// A utility function to do preorder traversal of BST
void preorder(Node *root)
{
    if (root != NULL)
    {
        printf("%d ", root->key);
        preorder(root->left);
        preorder(root->right);
    }
}
 
// Function for constructing all possible trees with
// given inorder traversal stored in an array from
// arr[start] to arr[end]. This function returns a
// vector of trees.
vector<Node *> getTrees(int arr[], int start, int end)
{
    // List to store all possible trees
    vector<Node *> trees;
 
    /* if start > end then subtree will be empty so
    returning NULL in the list */
    if (start > end)
    {
        trees.push_back(NULL);
        return trees;
    }
 
    /* Iterating through all values from start to end
        for constructing left and right subtree
        recursively */
    for (int i = start; i <= end; i++)
    {
        /* Constructing left subtree */
        vector<Node *> ltrees = getTrees(arr, start, i-1);
 
        /* Constructing right subtree */
        vector<Node *> rtrees = getTrees(arr, i+1, end);
 
        /* Now looping through all left and right subtrees
        and connecting them to ith root below */
        for (int j = 0; j < ltrees.size(); j++)
        {
            for (int k = 0; k < rtrees.size(); k++)
            {
                // Making arr[i] as root
                Node * node = newNode(arr[i]);
 
                // Connecting left subtree
                node->left = ltrees[j];
 
                // Connecting right subtree
                node->right = rtrees[k];
 
                // Adding this tree to list
                trees.push_back(node);
            }
        }
    }
    return trees;
}
 
// Driver Program to test above functions
int main()
{
    int in[] = {4, 5, 7};
    int n = sizeof(in) / sizeof(in[0]);
 
    vector<Node *> trees = getTrees(in, 0, n-1);
 
    cout << "Preorder traversals of different "
         << "possible Binary Trees are \n";
    for (int i = 0; i < trees.size(); i++)
    {
        preorder(trees[i]);
        printf("\n");
    }
    return 0;
}


Java




// Java program to find binary tree with given inorder
// traversal
import java.util.Vector;
 
/* Class containing left and right child of current
 node and key value*/
class Node {
    int data;
    Node left, right;
 
    public Node(int item) {
        data = item;
        left = null;
        right = null;
    }
}
 
/* Class to print Level Order Traversal */
class BinaryTree {
 
    Node root;
 
    // A utility function to do preorder traversal of BST
    void preOrder(Node node) {
        if (node != null) {
            System.out.print(node.data + " "    );
            preOrder(node.left);
            preOrder(node.right);
        }
    }
 
    // Function for constructing all possible trees with
    // given inorder traversal stored in an array from
    // arr[start] to arr[end]. This function returns a
    // vector of trees.
    Vector<Node> getTrees(int arr[], int start, int end) {
 
        // List to store all possible trees
        Vector<Node> trees= new Vector<Node>();
 
        /* if start > end then subtree will be empty so
         returning NULL in the list */
        if (start > end) {
            trees.add(null);
            return trees;
        }
 
        /* Iterating through all values from start to end
         for constructing left and right subtree
         recursively */
        for (int i = start; i <= end; i++) {
            /* Constructing left subtree */
            Vector<Node> ltrees = getTrees(arr, start, i - 1);
             
            /* Constructing right subtree */
            Vector<Node> rtrees = getTrees(arr, i + 1, end);
 
            /* Now looping through all left and right subtrees
             and connecting them to ith root below */
            for (int j = 0; j < ltrees.size(); j++) {
                for (int k = 0; k < rtrees.size(); k++) {
 
                    // Making arr[i] as root
                    Node node = new Node(arr[i]);
 
                    // Connecting left subtree
                    node.left = ltrees.get(j);
 
                    // Connecting right subtree
                    node.right = rtrees.get(k);
 
                    // Adding this tree to list
                    trees.add(node);
                }
            }
        }
        return trees;
    }
 
    public static void main(String args[]) {
        int in[] = {4, 5, 7};
        int n = in.length;
        BinaryTree tree = new BinaryTree();
        Vector<Node> trees = tree.getTrees(in, 0, n - 1);
        System.out.println("Preorder traversal of different "+
                           " binary trees are:");
        for (int i = 0; i < trees.size(); i++) {
            tree.preOrder(trees.get(i));
            System.out.println("");
        }
    }
}


Python3




# Python program to find binary tree with given
# inorder traversal
 
# Node Structure
class Node:
 
    # Utility to create a new node
    def __init__(self , item):
        self.key = item
        self.left = None
        self.right = None
 
# A utility function to do preorder traversal of BST
def preorder(root):
    if root is not None:
        print (root.key,end=" ")
        preorder(root.left)
        preorder(root.right)
 
 
# Function for constructing all possible trees with
# given inorder traversal stored in an array from
# arr[start] to arr[end]. This function returns a
# vector of trees.
def getTrees(arr , start , end):
 
    # List to store all possible trees
    trees = []
     
    """ if start > end then subtree will be empty so
    returning NULL in the list """
    if start > end :
        trees.append(None)
        return trees
     
 
    """ Iterating through all values from start to end
        for constructing left and right subtree
        recursively """
    for i in range(start , end+1):
 
        # Constructing left subtree
        ltrees = getTrees(arr , start , i-1)
         
        # Constructing right subtree
        rtrees = getTrees(arr , i+1 , end)
         
        """ Looping through all left and right subtrees
        and connecting to ith root below"""
        for j in ltrees :
            for k in rtrees :
 
                # Making arr[i]  as root
                node  = Node(arr[i])
     
                # Connecting left subtree
                node.left =
 
                # Connecting right subtree
                node.right = k
 
                # Adding this tree to list
                trees.append(node)
    return trees
 
# Driver program to test above function
inp = [4 , 5, 7]
n = len(inp)
 
trees = getTrees(inp , 0 , n-1)
 
print ("Preorder traversals of different possible\
 Binary Trees are ")
for i in trees :
    preorder(i);
    print ("")
 
# This program is contributed by Nikhil Kumar Singh(nickzuck_007)


C#




// C# program to find binary tree
// with given inorder traversal
using System;
using System.Collections.Generic;
 
/* Class containing left and right
   child of current node and key value*/
public class Node
{
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = null;
        right = null;
    }
}
 
/* Class to print Level Order Traversal */
class GFG
{
public Node root;
 
// A utility function to do
// preorder traversal of BST
public virtual void preOrder(Node node)
{
    if (node != null)
    {
        Console.Write(node.data + " ");
        preOrder(node.left);
        preOrder(node.right);
    }
}
 
// Function for constructing all possible
// trees with given inorder traversal
// stored in an array from arr[start] to
// arr[end]. This function returns a
// vector of trees.
public virtual List<Node> getTrees(int[] arr,
                                   int start,
                                   int end)
{
 
    // List to store all possible trees
    List<Node> trees = new List<Node>();
 
    /* if start > end then subtree will be
    empty so returning NULL in the list */
    if (start > end)
    {
        trees.Add(null);
        return trees;
    }
 
    /* Iterating through all values from
    start to end for constructing left
    and right subtree recursively */
    for (int i = start; i <= end; i++)
    {
        /* Constructing left subtree */
        List<Node> ltrees = getTrees(arr, start, i - 1);
 
        /* Constructing right subtree */
        List<Node> rtrees = getTrees(arr, i + 1, end);
 
        /* Now looping through all left and
        right subtrees and connecting them
        to ith root below */
        for (int j = 0; j < ltrees.Count; j++)
        {
            for (int k = 0; k < rtrees.Count; k++)
            {
 
                // Making arr[i] as root
                Node node = new Node(arr[i]);
 
                // Connecting left subtree
                node.left = ltrees[j];
 
                // Connecting right subtree
                node.right = rtrees[k];
 
                // Adding this tree to list
                trees.Add(node);
            }
        }
    }
    return trees;
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] arr = new int[] {4, 5, 7};
    int n = arr.Length;
    GFG tree = new GFG();
    List<Node> trees = tree.getTrees(arr, 0, n - 1);
    Console.WriteLine("Preorder traversal of different " +
                                    " binary trees are:");
    for (int i = 0; i < trees.Count; i++)
    {
        tree.preOrder(trees[i]);
        Console.WriteLine("");
    }
}
}
 
// This code is contributed by Shrikant13


Javascript




<script>
  
// Javascript program to find binary tree
// with given inorder traversal
 
/* Class containing left and right
   child of current node and key value*/
class Node
{
    constructor(item)
    {
        this.data = item;
        this.left = null;
        this.right = null;
    }
}
 
/* Class to print Level Order Traversal */
 
var root = null;
 
// A utility function to do
// preorder traversal of BST
function preOrder(node)
{
    if (node != null)
    {
        document.write(node.data + " ");
        preOrder(node.left);
        preOrder(node.right);
    }
}
 
// Function for constructing all possible
// trees with given inorder traversal
// stored in an array from arr[start] to
// arr[end]. This function returns a
// vector of trees.
function getTrees(arr, start, end)
{
 
    // List to store all possible trees
    var trees = [];
 
    /* if start > end then subtree will be
    empty so returning NULL in the list */
    if (start > end)
    {
        trees.push(null);
        return trees;
    }
 
    /* Iterating through all values from
    start to end for constructing left
    and right subtree recursively */
    for (var i = start; i <= end; i++)
    {
        /* Constructing left subtree */
        var ltrees = getTrees(arr, start, i - 1);
 
        /* Constructing right subtree */
        var rtrees = getTrees(arr, i + 1, end);
 
        /* Now looping through all left and
        right subtrees and connecting them
        to ith root below */
        for (var j = 0; j < ltrees.length; j++)
        {
            for (var k = 0; k < rtrees.length; k++)
            {
 
                // Making arr[i] as root
                var node = new Node(arr[i]);
 
                // Connecting left subtree
                node.left = ltrees[j];
 
                // Connecting right subtree
                node.right = rtrees[k];
 
                // Adding this tree to list
                trees.push(node);
            }
        }
    }
    return trees;
}
 
// Driver Code
var arr = [4, 5, 7];
var n = arr.length;
var trees = getTrees(arr, 0, n - 1);
document.write("Preorder traversal of different " +
                                " binary trees are:<br>");
for(var i = 0; i < trees.length; i++)
{
    preOrder(trees[i]);
    document.write("<br>");
}
 
// This code is contributed by rrrtnx.
 
</script>


Output: 
 

Preorder traversals of different possible Binary Trees are 
4 5 7 
4 7 5 
5 4 7 
7 4 5 
7 5 4

Time Complexity: O(n^3).
The time complexity of the above algorithm is O(n^3). The getTrees() function is called for every element of the array. Inside the function, two for loops are used for constructing left and right subtrees for every element of the array.

Space Complexity: O(n^2).
The space complexity of the above algorithm is O(n^2). The getTrees() function is called for every element of the array. Inside the function, two for loops are used for constructing left and right subtrees for every element of the array. Vector of size n is used for storing the list of trees.

Thanks to Utkarsh for suggesting above solution.
This problem is similar to the problem discussed here.

 



Previous Article
Next Article

Similar Reads

Total number of possible Binary Search Trees and Binary Trees with n keys
Total number of possible Binary Search Trees with n different keys (countBST(n)) = Catalan number Cn = (2n)! / ((n + 1)! * n!) For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees. Total number of possible Binary Trees with n different keys (countBT(n)) = countBST(n
12 min read
Construct Special Binary Tree from given Inorder traversal
Given Inorder Traversal of a Special Binary Tree in which the key of every node is greater than keys in left and right children, construct the Binary Tree and return root. Examples: Input: inorder[] = {5, 10, 40, 30, 28} Output: root of following tree 40 / \ 10 30 / \ 5 28 Input: inorder[] = {1, 5, 10, 40, 30, 15, 28, 20} Output: root of following
14 min read
Calculate height of Binary Tree using Inorder and Level Order Traversal
Given inorder traversal and Level Order traversal of a Binary Tree. The task is to calculate the height of the tree without constructing it. Example: Input : Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output : 4 The binary tree that ca
12 min read
Check if Inorder traversal of a Binary Tree is palindrome or not
Given a binary tree and the task if to check if its Inorder Sequence is a palindrome or not. Examples: Input: Output: True Explanation: The Inorder sequence of the tree is "bbaaabb" which is a palindromic string.Input: Output: False Explanation: The Inorder sequence of the tree is "bbdaabb" which is not a palindromic string. Approach: To solve the
8 min read
Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order tr
13 min read
Binary Tree Iterator for Inorder Traversal
Given a Binary Tree and an input array. The task is to create an Iterator that utilizes next() and hasNext() functions to perform Inorder traversal on the binary tree. Examples: Input: 8 Input Array = [next(), hasNext(), next(), next(), next(), hasNext(), next(), next(), hasNext()] / \ 3 9 / \ 2 4 \ 5 Output: [2, true, 3, 4, 5, true, 8, 9, false] E
13 min read
Inorder Traversal of Binary Tree
Inorder traversal is defined as a type of tree traversal technique which follows the Left-Root-Right pattern, such that: The left subtree is traversed firstThen the root node for that subtree is traversedFinally, the right subtree is traversed Algorithm for Inorder Traversal of Binary Tree The algorithm for inorder traversal is shown as follows: In
6 min read
Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
We have discussed Thread based Morris Traversal. Can we do inorder traversal without threads if we have parent pointers available to us? Input: Root of Below Tree [Every node of tree has parent pointer also] 10 / \ 5 100 / \ 80 120 Output: 5 10 80 100 120 The code should not extra space (No Recursion and stack) In inorder traversal, we follow "left
11 min read
Convert Binary Tree to Doubly Linked List using inorder traversal
Given a Binary Tree (Bt), convert it to a Doubly Linked List(DLL). The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as in Inorder for the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the
15+ min read
Find n-th node of inorder traversal
Given the binary tree and you have to find out the n-th node of inorder traversal. Examples: Input : n = 4 10 / \ 20 30 / \ 40 50 Output : 10 Inorder Traversal is : 40 20 50 10 30 Input : n = 3 7 / \ 2 3 / \ 8 5 Output : 8 Inorder: 2 7 8 3 5 3th node is 8 We do simple Inorder Traversal. While doing the traversal, we keep track of the count of nodes
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg