Nested List Weight Sum(dfs,bfs)
Example
"""
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
class NestedInteger(object):
def isInteger(self):
# @return {boolean} True if this NestedInteger holds a single integer,
# rather than a nested list.
def getInteger(self):
# @return {int} the single integer that this NestedInteger holds,
# if it holds a single integer
# Return None if this NestedInteger holds a nested list
def getList(self):
# @return {NestedInteger[]} the nested list that this NestedInteger holds,
# if it holds a nested list
# Return None if this NestedInteger holds a single integer
"""
class Solution(object):
# @param {NestedInteger[]} nestedList a list of NestedInteger Object
# @return {int} an integer
def depthSum(self, nestedList):
# Write your code here
return self.dfs(nestedList,1)
def dfs(self,nestedList,level):
ans = 0
if not nestedList:
return ans
for i in nestedList:
if i.isInteger():
ans+= i.getInteger() * level
else:
ans += self.dfs(i.getList(),level+1)
return ansLast updated