给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \
3 2 1 1 3 2
/ / \
2 1 2 3
/flowchart.js/
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
# 递归超时
# if(n<1):
# return 1
# sum=0
# for i in range(1,n+1):
# sum+= self.numTrees(i-1)*self.numTrees(n-i)
# return sum
if n==0 or n==1:
return 1
l_num=[]
l_num.append(1)
l_num.append(1)
for i in range(2,n+1):
sum=0
print(i)
for j in range(0,i):
print(j)
sum=sum+l_num[j]*l_num[i-j-1]
l_num.append(sum)
return l_num[n]