Python using iterator


  • 1
    R

    This problem is a good example for usage of iterator.

    class Solution(object):
        def generateTrees(self, n):
            """
            :type n: int
            :rtype: List[TreeNode]
            """
            if n <= 0:
                return []
            def build(i, j):
                if i > j:
                    yield None
                for k in range(i, j+1):
                    for left in build(i, k-1):
                        for right in build(k+1, j):
                            node = TreeNode(k)
                            node.left = left
                            node.right = right
                            yield node
            return [node for node in build(1, n)]
    

  • 0
    S

    Beautiful. Iterators done right on so many levels


Log in to reply
 

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