A straightforward python solution


  • 5
    K
    from itertools import product
    
    class Solution:
        # @param {integer} n
        # @return {TreeNode[]}
        def generateTrees(self, n):
            return self.BST([i+1 for i in range(n)])
            
        def BST(self, nodes):
            trees = []
            for i in range(len(nodes)):
                for leftSubTree, rightSubTree in product(self.BST(nodes[:i]), self.BST(nodes[i+1:])):
                    root = TreeNode(nodes[i])
                    root.left, root.right = leftSubTree, rightSubTree
                    trees.append(root)
                
            return trees or [None]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.