Unique Binary Search Trees
Medium
BSTDynamic ProgrammingMath
Problem
Return the number of structurally unique BSTs that store values 1..n.
Example 1
Input: n=3
Output: 5
Example 2
Input: n=1
Output: 1
Constraints
- 1 ≤ n ≤ 19
Approach — Dynamic Programming
This is a Dynamic Programming problem. The idea: break the problem into overlapping subproblems and build the answer up, caching results so nothing is recomputed. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) to O(n²) time.
Solution code
Python
class Solution:
def numTrees(self, n):
dp = [1] * (n + 1)
for nodes in range(2, n + 1):
total = 0
for root in range(1, nodes + 1):
total += dp[root - 1] * dp[nodes - root]
dp[nodes] = total
return dp[n]
Java
class Solution {
public int numTrees(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
for (int i = 1; i <= n; i++)
for (int j = 0; j < i; j++)
dp[i] += dp[j] * dp[i - 1 - j];
return dp[n];
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Unique Binary Search Trees interactively → ← All solutions