Class Solution
java.lang.Object
g0001_0100.s0096_unique_binary_search_trees.Solution
96 - Unique Binary Search Trees.
Medium
Given an integer n, return the number of structurally unique **BST’**s (binary search trees) which has exactly n nodes of unique values from 1 to n.
Example 1:

Input: n = 3
Output: 5
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 19
To solve the “Unique Binary Search Trees” problem in Java with the Solution class, follow these steps:
- Define a method
numTreesin theSolutionclass that takes an integernas input and returns the number of structurally unique BSTs (binary search trees) with exactlynnodes. - Implement a dynamic programming approach to solve the problem:
- Create an array
dpof sizen + 1to store the number of unique BSTs for each number of nodes from 0 ton. - Initialize
dp[0] = 1anddp[1] = 1, as there is only one unique BST for 0 and 1 node(s). - Use a nested loop to calculate
dp[i]for eachifrom 2 ton. - For each
i, calculatedp[i]by summing up the products ofdp[j]anddp[i - j - 1]for all possible values ofjfrom 0 toi - 1. - Return
dp[n], which represents the number of unique BSTs withnnodes.
- Create an array
Here’s the implementation of the numTrees method in Java:
class Solution {
public int numTrees(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 0; j < i; j++) {
dp[i] += dp[j] * dp[i - j - 1];
}
}
return dp[n];
}
}
This implementation uses dynamic programming to compute the number of structurally unique BSTs with n nodes in O(n^2) time complexity.
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
Solution
public Solution()
-
-
Method Details
-
numTrees
public int numTrees(int n)
-