Input: n =3Output: 5Explanation: The five distinct binary trees for3 nodes are:1) All nodes as a left-skewed tree.2) All nodes as a right-skewed tree.3) Root with a left child and a left child's right child.4) Root with a right child and a right child's left child.5) Root with two children(one left and one right).
graph TD
%% Tree 1: All as a left-skewed tree
A1(" ") --> B1(" ")
A1 ~~~ N11:::hidden
B1(" ") --> C1(" ")
B1 ~~~ N12:::hidden
%% Tree 2: All as a right-skewed tree
A2(" ") ~~~ N21:::hidden
A2 --> B2(" ")
B2(" ") ~~~ N22:::hidden
B2 --> C2(" ")
%% Tree 3: Root with a left child, and left child's left child
A3(" ") --> B3(" ")
A3 ~~~ N31:::hidden
B3(" ") ~~~ N32:::hidden
B3 --> C3(" ")
%% Tree 4: Root with a left child, and left child's right child
A4 ~~~ N41:::hidden
A4(" ") --> B4(" ")
B4(" ") --- C4(" ")
B4 ~~~ N42:::hidden
%% Tree 5: Root with two children (left and right)
A5(" ") --> B5(" ")
A5(" ") --> C5(" ")
classDef hidden display:none
The number of distinct binary trees with n nodes, denoted as C(n), is determined by combining trees with a root, a left subtree of j nodes, and a right subtree of (n - 1) - j nodes for all possible values of j. This can be expressed as:
1
C(n) = C(0)C(n-1) + C(1)C(n-2) + ... + C(n-1)C(0)
The recursive formula is:
$$
C_n = \sum_{i=0}^{n-1} C_i \cdot C_{n-i-1}
$$
Use a dynamic programming or iterative solution to compute Catalan numbers for n nodes. This avoids direct factorial computation and reduces complexity.
Base case: (C_0 = 1) (An empty tree is one type of tree).