Python Fast and Elegant Solution

  • 0
    # 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 generateTrees(self, n):
            :type n: int
            :rtype: List[TreeNode]
            def construct(low, high):
                if low > high: return [None]
                if low == high: return [TreeNode(low)]
                ans = []
                for i in range(low, high+1):
                    left = construct(low, i-1)
                    right = construct(i+1, high)
                    for l in left:
                        for r in right:
                            root = TreeNode(i)
                            root.left, root.right = l, r
                return ans
            return filter(lambda x: x, construct(1, n))

Log in to reply

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