Python recursive solution


  • 0
    A
    
    class NestedIterator(object):
        def __init__(self, nestedList):
            self.nestedList = nestedList
            self.i = 0
            self.currIterator = None
    
        def next(self):
            if self.currIterator:
                ret = self.currIterator.next()
            else:
                ret = self.nestedList[self.i].getInteger()
                self.i += 1
            return ret
            
        def hasNext(self):
            if self.i == len(self.nestedList):
                return False
            if self.nestedList[self.i].isInteger():
                return True
            else:
                if not self.currIterator:
                    self.currIterator = NestedIterator(self.nestedList[self.i].getList())
                if not self.currIterator.hasNext():
                    self.currIterator = None
                    self.i += 1
                    return self.hasNext()
                else:
                    return True
           
    

Log in to reply
 

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