• Time:O(n)
• Space:O(n)

## C++

class Solution {
public:
int depthSum(vector<NestedInteger>& nestedList) {
int ans = 0;
int depth = 0;
queue<NestedInteger> q;

while (!q.empty()) {
++depth;
for (int sz = q.size(); sz > 0; --sz) {
const auto ni = q.front();
q.pop();
if (ni.isInteger())
ans += ni.getInteger() * depth;
else
}
}

return ans;
}

private:
const vector<NestedInteger>& nestedList) {
for (const auto& ni : nestedList)
q.push(ni);
}
};

## JAVA

class Solution {
public int depthSum(List<NestedInteger> nestedList) {
int ans = 0;
int depth = 0;
Queue<NestedInteger> q = new ArrayDeque<>();

while (!q.isEmpty()) {
++depth;
for (int sz = q.size(); sz > 0; --sz) {
final NestedInteger ni = q.poll();
if (ni.isInteger())
ans += ni.getInteger() * depth;
else
}
}

return ans;
}

private void addIntegers(Queue<NestedInteger> q, List<NestedInteger> nestedList) {
for (final NestedInteger ni : nestedList)
q.offer(ni);
}
}

## Python

class Solution:
def depthSum(self, nestedList: List[NestedInteger]) -> int:
ans = 0
depth = 0
q = deque()

for ni in nestedList:
q.append(ni)

while q:
depth += 1
for _ in range(len(q)):
ni = q.popleft()
if ni.isInteger():
ans += ni.getInteger() * depth
else:

return ans

• Time:O(n)
• Space:O(h)

## C++

class Solution {
public:
int depthSum(vector<NestedInteger>& nestedList) {
int ans = 0;
dfs(nestedList, 1, ans);
return ans;
}

private:
void dfs(const vector<NestedInteger>& nestedList, int depth, int& ans) {
for (const auto& ni : nestedList)
if (ni.isInteger())
ans += ni.getInteger() * depth;
else
dfs(ni.getList(), depth + 1, ans);
}
};

## JAVA

class Solution {
public int depthSum(List<NestedInteger> nestedList) {
dfs(nestedList, 1);
return ans;
}

private int ans = 0;

private void dfs(final List<NestedInteger> nestedList, int depth) {
for (final NestedInteger ni : nestedList)
if (ni.isInteger())
ans += ni.getInteger() * depth;
else
dfs(ni.getList(), depth + 1);
}
}

## Python

class Solution:
def depthSum(self, nestedList: List[NestedInteger]) -> int:
ans = 0

def dfs(nestedList: List[NestedInteger], depth: int) -> None:
nonlocal ans
for ni in nestedList:
if ni.isInteger():
ans += ni.getInteger() * depth
else:
dfs(ni.getList(), depth + 1)

dfs(nestedList, 1)
return ans