Unique Binary Search Trees
franklinqin0 DPTreeCatalan Number
Read more about Catalan_number on Wikipedia (opens new window) and this great Chinese post (opens new window).
# Solution
means the n
th Catalna number.
The first Catalan numbers for are: ...
The number of structurally unique BST's that store values is .
# Catalan Number
All following solutions use some formula to calculate n
th Catalan number.
# Recursive Formula 1
Complexity
time:
space:
def numTrees(self, n: int) -> int:
C = [0 for _ in range(n+1)]
C[0] = C[1] = 1
for i in range(2,n+1):
for j in range(1,i+1):
C[i] += C[j-1]*C[i-j]
return C[n]
1
2
3
4
5
6
7
2
3
4
5
6
7
# Recursive Formula 2
Complexity
time:
space:
def numTrees(self, n: int) -> int:
C = 1
for i in range(1, n+1):
C = C * 2*(2*i-1)//(i+1)
return C
1
2
3
4
5
2
3
4
5
# Binomial Coefficients
Complexity
time:
space:
def numTrees(self, n: int) -> int:
C = 1
for k in range(2,n+1):
C = C*(n+k)/k
return round(C)
1
2
3
4
5
2
3
4
5