【LeetCode】【Python题解】Unique Binary Search Trees

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


【LeetCode】【Python题解】Unique Binary Search Trees

上一篇:七日Python之路--第三天(之不安分 wxPython)


下一篇:关于 java.util.concurrent 您不知道的 5 件事--转