3-line Python solution, easy to understand

  • 2
    def depthSum(self, nestedList):
        :type nestedList: List[NestedInteger]
        :rtype: int
        def scanList(curr_list, depth):
            return sum(depth * x.getInteger() if x.isInteger() else scanList(x.getList(), depth + 1) for x in curr_list)
        return scanList(nestedList, 1)

  • 0

    @kitt Hey good answer. Any idea why a similar approach is not working? It seems passing the value down the recursive function does not preserve the val of totalSum. Any idea on how to resolve this?

    def depthSum(lst, height, totalSum):
        for i in lst:
            #print 'lst is ', lst
            if isinstance(i, list):
                depthSum(i, height + 1, totalSum) # depthsum([1,1],
            elif isinstance(i, int):
                tmp = i * height
                totalSum += tmp
        return totalSum

    EDIT: nevermind. I had to save the return from depthSum into totalSum. But do you see any problems with this method or way of programming? Looking to improve on this..

Log in to reply

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