Number of Binary Trees for given Preorder Sequence length - GeeksforGeeks

30 Apr, 2021
Count the number of Binary Tree possible for a given Preorder Sequence length n.Examples:  
Input : n = 1
Output : 1

Input : n = 2
Output : 2

Input : n = 3
Output : 5
 
 
Background :
In Preorder traversal, we process the root node first, then traverse the left child node and then right child node. For example preorder traversal of below tree is 1 2 4 5 3 6 7  
 
Finding number of trees with given Preorder:
Number of Binary Tree possible if such a traversal length (let’s say n) is given.Let’s take an Example : Given Preorder Sequence –> 2 4 6 8 10 (length 5).  
Assume there is only 1 node (that is 2 in this case), So only 1 Binary tree is Possible
Now, assume there are 2 nodes (namely 2 and 4), So only 2 Binary Tree are Possible:
Now, when there are 3 nodes (namely 2, 4 and 6), So Possible Binary tree are 5
Consider 4 nodes (that are 2, 4, 6 and 8), So Possible Binary Tree are 14. Let’s say BT(1) denotes number of Binary tree for 1 node. (We assume BT(0)=1) BT(4) = BT(0) * BT(3) + BT(1) * BT(2) + BT(2) * BT(1) + BT(3) * BT(0) BT(4) = 1 * 5 + 1 * 2 + 2 * 1 + 5 * 1 = 14
Similarly, considering all the 5 nodes (2, 4, 6, 8 and 10). Possible number of Binary Tree are: BT(5) = BT(0) * BT(4) + BT(1) * BT(3) + BT(2) * BT(2) + BT(3) * BT(1) + BT(4) * BT(0) BT(5) = 1 * 14 + 1 * 5 + 2 * 2 + 5 * 1 + 14 * 1 = 42
 
Hence, Total binary Tree for Pre-order sequence of length 5 is 42.We use Dynamic programming to calculate the possible number of Binary Tree. We take one node at a time and calculate the possible Trees using previously calculated Trees.  
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to count possible binary trees// using dynamic programming#include <bits/stdc++.h>using namespace std; int countTrees(int n){    // Array to store number of Binary tree    // for every count of nodes    int BT[n + 1];    memset(BT, 0, sizeof(BT));     BT[0] = BT[1] = 1;     // Start finding from 2 nodes, since    // already know for 1 node.    for (int i = 2; i <= n; ++i)        for (int j = 0; j < i; j++)            BT[i] += BT[j] * BT[i - j - 1];     return BT[n];} // Driver codeint main(){    int n = 5;    cout << "Total Possible Binary Trees are : "        << countTrees(n) << endl;    return 0;}
// Java Program to count// possible binary trees// using dynamic programmingimport java.io.*; class GFG{static int countTrees(int n){    // Array to store number    // of Binary tree for    // every count of nodes    int BT[] = new int[n + 1];    for(int i = 0; i <= n; i++)    BT[i] = 0;    BT[0] = BT[1] = 1;     // Start finding from 2    // nodes, since already    // know for 1 node.    for (int i = 2; i <= n; ++i)        for (int j = 0; j < i; j++)            BT[i] += BT[j] *                     BT[i - j - 1];     return BT[n];} // Driver codepublic static void main (String[] args){int n = 5;System.out.println("Total Possible " +                "Binary Trees are : " +                       countTrees(n));}} // This code is contributed by anuj_67.
# Python3 Program to count possible binary# trees using dynamic programming def countTrees(n) :     # Array to store number of Binary    # tree for every count of nodes    BT = [0] * (n + 1)     BT[0] = BT[1] = 1     # Start finding from 2 nodes, since    # already know for 1 node.    for i in range(2, n + 1):        for j in range(i):            BT[i] += BT[j] * BT[i - j - 1]     return BT[n] # Driver Codeif __name__ == '__main__':     n = 5    print("Total Possible Binary Trees are : ",                                 countTrees(n))                                  # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# Program to count// possible binary trees// using dynamic programmingusing System; class GFG{static int countTrees(int n){    // Array to store number    // of Binary tree for    // every count of nodes    int []BT = new int[n + 1];    for(int i = 0; i <= n; i++)        BT[i] = 0;        BT[0] = BT[1] = 1;     // Start finding from 2    // nodes, since already    // know for 1 node.    for (int i = 2; i <= n; ++i)        for (int j = 0; j < i; j++)            BT[i] += BT[j] *                     BT[i - j - 1];     return BT[n];} // Driver codestatic public void Main (String []args){    int n = 5;    Console.WriteLine("Total Possible " +                      "Binary Trees are : " +                             countTrees(n));}} // This code is contributed// by Arnab Kundu
<?php// PHP Program to count possible binary// trees using dynamic programming function countTrees($n){    // Array to store number of Binary    // tree for every count of nodes    $BT[$n + 1] = array();    $BT = array_fill(0, $n + 1, NULL);    $BT[0] = $BT[1] = 1;     // Start finding from 2 nodes, since    // already know for 1 node.    for ($i = 2; $i <= $n; ++$i)        for ($j = 0; $j < $i; $j++)            $BT[$i] += $BT[$j] *                       $BT[$i - $j - 1];     return $BT[$n];} // Driver code$n = 5;echo "Total Possible Binary Trees are : ",                    countTrees($n), "\n"; // This code is contributed by ajit.?>
<script>    // Javascript Program to count    // possible binary trees    // using dynamic programming         function countTrees(n)    {        // Array to store number        // of Binary tree for        // every count of nodes        let BT = new Array(n + 1);        for(let i = 0; i <= n; i++)            BT[i] = 0;            BT[0] = BT[1] = 1;         // Start finding from 2        // nodes, since already        // know for 1 node.        for (let i = 2; i <= n; ++i)            for (let j = 0; j < i; j++)                BT[i] += BT[j] * BT[i - j - 1];         return BT[n];    }         let n = 5;    document.write("Total Possible " + "Binary Trees are : " + countTrees(n));                              </script>
Output:  
Total Possible Binary Trees are : 42
Alternative : This can also be done using 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.This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
vt_m
andrew1234
jit_t
SHUBHAMSINGH10
divyesh072019
catalan
Combinatorial
Tree
Combinatorial
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Factorial of a large number
Count ways to reach the nth stair using step 1, 2 or 3
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion