One pass recursive solution


  • 0
    Z

    The idea is simple, just carry the sum of all value in the current level into next level.

    e.g.
    [1,[2,[3]]]
    This becomes:
    [1 + [1 + 2, [3]]] => [1 + 3 + [3 + 3]] => 1 + 3 + 6 => 10

    class Solution(object):
        def depthSumInverse(self, nestedList, total=0):
            if not nestedList: return 0
            lists = []
            for val in nestedList:
                if val.isInteger():
                    total += val.getInteger()
                else:
                    lists += val.getList()
            return total + self.depthSumInverse(lists, total)
    

Log in to reply
 

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