Skip to content

Commit 1253056

Browse files
authored
Create 01 - Recursive Approach.cpp
1 parent 2eaf7a9 commit 1253056

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public:
3+
int numTrees(int n) {
4+
// Base case: If there are 0 or 1 nodes, there is only 1 unique BST possible.
5+
if(n <= 1) return 1;
6+
7+
int ans = 0; // Initialize the variable to store the total number of unique BSTs.
8+
9+
// Loop through each number i from 1 to n.
10+
// Treat 'i' as the root of the BST.
11+
for(int i = 1; i <= n; i++) {
12+
// Recursively calculate the number of unique BSTs for the left and right subtrees.
13+
// Left subtree has (i-1) nodes.
14+
// Right subtree has (n-i) nodes.
15+
ans += numTrees(i-1) * numTrees(n-i);
16+
}
17+
18+
// Return the total count of unique BSTs for n nodes.
19+
return ans;
20+
}
21+
};

0 commit comments

Comments
 (0)