![]() |
VOOZH | about |
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).
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.
Output:
Total Possible Binary Trees are : 42
Time Complexity: O(n2)
Auxiliary Space : O(n)
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.