Sunday, September 7, 2014

Leetcode: Unique Binary Search Trees @Python

Math problem. The number of the unique BST is the number of the unique left sub-trees times that of the right sub-trees.
class Solution:
    # @return an integer
    def numTrees(self, n):
        if n==0:
            return 0
        elif n==1:
            return 1
        elif n==2:
            return 2
        else:
            num=2*self.numTrees(n-1)
            for i in range(1,n-1):
                num+=self.numTrees(i)*self.numTrees(n-1-i)
            return num

No comments :

Post a Comment