python stack iterative solution(Similar to 'Flatten Nested List Iterator')


  • 0
    L

    Put everything into a stack. If the top element == 'end', decrement the depth. If the top element == Integer, do the calulcation. Else put the nested list on to the stack and increment the depth.

    class Solution(object):
        def depthSum(self, nestedList):
            """
            :type nestedList: List[NestedInteger]
            :rtype: int
            """
            if not nestedList:
                return 0
            
            st = nestedList[::-1]
            res = 0
            depth = 1
            while st:
                cur = st.pop()
                if cur == 'end':
                    depth -= 1
                elif cur.isInteger():
                    res += cur.getInteger() * depth
                else:
                    lst = cur.getList()
                    depth += 1
                    st = st + ['end'] + lst[::-1]
            return res
    

Log in to reply
 

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