You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists.
The depth of an integer is the number of lists that it is inside of. For example, the nested list [1 ,[2,2],[ [3],2],1 ] has each integer’s value set to its depth. Let maxDepth be the maximum depth of any integer.
The weight of an integer is maxDepth - (the depth of the integer) + 1.
Return the sum of each integer innestedListmultiplied by its weight.
Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.
// This is the interface that allows for creating nested lists.// You should not implement it, or speculate about its implementationpublicinterfaceNestedInteger {
// Constructor initializes an empty nested list.publicNestedInteger();
// Constructor initializes a single integer.publicNestedInteger(int value);
// @return true if this NestedInteger holds a single integer, rather than a// nested list.publicbooleanisInteger();
// @return the single integer that this NestedInteger holds, if it holds a// single integer Return null if this NestedInteger holds a nested listpublic Integer getInteger();
// Set this NestedInteger to hold a single integer.publicvoidsetInteger(int value);
// Set this NestedInteger to hold a nested list and adds a nested integer to// it.publicvoidadd(NestedInteger ni);
// @return the nested list that this NestedInteger holds, if it holds a// nested list// Return empty list if this NestedInteger holds a single integerpublic List<NestedInteger>getList();
}
classNestedInteger:
def __init__(self, value=None):
"""
If value is not specified, initializes an empty list.
Otherwise initializes a single integer equal to value.
"""defisInteger(self):
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
:rtype bool
"""defadd(self, elem):
"""
Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
:rtype void
"""defsetInteger(self, value):
"""
Set this NestedInteger to hold a single integer equal to value.
:rtype void
"""defgetInteger(self):
"""
@return the single integer that this NestedInteger holds, if it holds a single integer
Return None if this NestedInteger holds a nested list
:rtype int
"""defgetList(self):
"""
@return the nested list that this NestedInteger holds, if it holds a nested list
Return None if this NestedInteger holds a single integer
:rtype List[NestedInteger]
"""
Time: O(n), where n is the total number of nested integers and lists. Each element is visited a constant number of times in both findMaxDepth and weightedDepthSum.
Space: O(d), where d is the maximum depth of the nested list. This accounts for the space used by the recursion stack.