Python solution with detailed explanation

  • 0


    Nested List Weight Sum

    • We use a simple DFS to compute the nested list weight.The outermost list has level 1.
    • Beyond that we just need to loop across all items in the nested list. If item is an integer, update the weighted sum. Otherwise make a recursive call with the nested list and updated level.
    class Solution(object):
        def depthSum(self, nestedList):
            :type nestedList: List[NestedInteger]
            :rtype: int
            self.d_sum = 0
            self.helper(nestedList, 1)
            return self.d_sum
        def helper(self, nestedList, level):
            for x in nestedList:
                if x.isInteger():
                    self.d_sum = self.d_sum + x.getInteger()*level
                    self.helper(x.getList(), level+1)

Log in to reply

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