题目:
给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
思路:
首先,根节点共有n种可能性。二叉搜索树的种类就等于这n种情况的种类之和。当根为x(1<x<=n)时,树的种类为左子树的种类✖右子树的种类。当子树的节点数为0或1时,种类数为1。
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 1
if n == 1:
return 1
res = 0
for i in range(n):
res += self.numTrees(i) * self.numTrees(n-i-1)
return res