蠡口95. Unique Binary Search Trees II

Inspired by LC96. Unique Binary Search Trees, the use of recursion. Comprising i ... j should be taken well by BST k (i≤k≤j), then comprising i .. (k-1) comprises a BST + k + (k + 1) .. j of BST, as shown below shows.

It contains all BST I ... J k is taken over all look As root, comprising from i .. (k-1) remove all BST as a left root, and contains from (k + 1) .. j all BST as a right root is taken. 1 ... n Returns all BST is also desired.

Complexity Analysis time: 1 to assume BST n is the number of all the BST n- , there is the BST n- = ΣBST K * the BST n--K-1, then the BST n- is Cattleya number, which is the general term formula H n- = C n- 2N / (n-+. 1). see derived here .

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def helper(self,i,j):
        if j<i: return([None])
        if i==j: return([TreeNode(i)])
        ans=[]
        for k in range(i,j+1):
            left=self.helper(i,k-1)
            right=self.helper(k+1,j)
            for l in left:
                for r in right:
                    root=TreeNode(k)
                    root.left,root.right=l,r
                    ans.append(root)
        return (years)
    
    def generateTrees(self, n):
        """
        :type n: int
        :rtype: List[TreeNode]
        """
        if n<=0: return([])
        if n==1: return([TreeNode(1)])
        return(self.helper(1,n))

 

Guess you like

Origin www.cnblogs.com/Leisgo/p/11697692.html