Simple python solution using yield

  • 0

    I know we should use stack instead :)

    class NestedIterator(object):
        def flatten(self, nestedList):
            for x in nestedList:
                if x.isInteger(): 
                    yield x.getInteger()
                    for y in self.flatten(x.getList()):
                        yield y
        def __init__(self, nestedList):
            self.f = self.flatten(nestedList)
        def next(self):
            return self.v
        def hasNext(self):
            self.v = next(self.f, None)
            if self.v == None: return False
            return True

Log in to reply

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