Given n, how many structurally unique BST‘s (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST‘s.
1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3
题目大意很简单,就是计算有多少个不同的二叉寻找树满足前序遍历是1,2,3...n的条件
思路:每一棵树都是由根节点,左子树,右子树构成,一旦确定根节点是x的同时,
左子树只能由1,2,3...x-1构成,同理右子树由x+1,x+2...n构成,递归可求解
class Solution: # @return an integer def numTrees(self, n): if n == 0 or n == 1: return 1 elif n ==2: return 2 else: ans = 0 for i in range(0,n): ans += self.numTrees(i)*self.numTrees(n-i-1) return ans
时间: 2024-11-05 06:00:34