Share my Python solution with `yield`. Just for fun.

  • 1

    using python keyword yield to create a generator.

    class NestedIterator(object):

    def __init__(self, nestedList):
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        self._gen = self.gen(nestedList)
        self.res = None
    def gen(self, a):
        for x in a:
            if x.isInteger():
                yield x.getInteger()
                for y in self.gen(x.getList()):
                    yield y
    def next(self):
        :rtype: int
        return self.res
    def hasNext(self):
        :rtype: bool
            self.res =
        except Exception as e:
            return False
        return True

Log in to reply

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