Share my 11 lines Python code


  • 3
    X
    def helper(self, n, start):
        ret = []
        for i in range(start, n + start):
            l = self.helper(i - start, start)
            r = self.helper(n + start - i - 1, i + 1)
            for x in (l if len(l) else [None]):
                for y in (r if len(r) else [None]):
                    root = TreeNode(i)
                    root.left, root.right = x, y
                    ret.append(root)
        return ret
    def generateTrees(self, n):
        return self.helper(n, 1)
    

    Pretty standard top-down recursive approach. "start" is the starting number for tree node labeling.


Log in to reply
 

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