BFS:
class Solution:
def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
res = 0
Sum = 0
while (len(nestedList) > 0):
new_nestedList = []
for ele in nestedList:
if ele.isInteger():
Sum += ele.getInteger()
else:
new_nestedList += ele.getList()
nestedList = new_nestedList
res += Sum
return res
DFS:
class Solution:
def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
self.Cache = collections.defaultdict(int)
self.maxdepth = 0
for ele in nestedList:
self.dfs(ele, 1)
res = 0
for weight, num in self.Cache.items():
res += (self.maxdepth - weight + 1)*num
return res
def dfs(self, nestedList, depth):
self.maxdepth = max(depth, self.maxdepth)
if nestedList.isInteger():
self.Cache[depth] += nestedList.getInteger()
return
List = nestedList.getList()
for ele in List:
self.dfs(ele, depth+1)