Resursive Python Code


  • 2
    R
    class Solution(object):
        def depthSum(self, nestedList):
            """
            :type nestedList: List[NestedInteger]
            :rtype: int
            """
            return self.depthPartialSum(nestedList, 0)
            
        def depthPartialSum(self, List, depth):
            sum = 0
            for i in List:
                if i.isInteger():
                    sum += i.getInteger() * (depth + 1)
                else:
                    sum += self.depthPartialSum(i.getList(), depth + 1)
            return sum
    

  • 0
    B

    Since there is no depth of 0, it might be clearer to start the depth at 1.

     depthPartialSum(self, List, depth=1):
        sum = 0
        for i in List:
            if i.isInteger():
                sum += i.getInteger() * depth
            else:
                sum += self.depthPartialSum(i.getList(), depth + 1)
        return sum
    

Log in to reply
 

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