Nested List Weight SumII(dfs,bfs)
"""
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.
if self.
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):
if not nestedList:
return 0
curlevel=level=1
ans = 0
anslist = []
for i in nestedList:
if i.isInteger():
anslist.append(i.getInteger())
else:
ans,level = self.dfs(i.getList())
curlevel = max(curlevel,level)
anslist.append(ans)
return (curlevel,sum(anslist)*curlevel)Last updated