Skip to content

364. Nested List Weight Sum II

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int depthSumInverse(vector<NestedInteger>& nestedList) {
    int ans = 0;
    int prevSum = 0;
    queue<NestedInteger> q{{nestedList.begin(), nestedList.end()}};

    while (!q.empty()) {
      for (int sz = q.size(); sz > 0; --sz) {
        const NestedInteger ni = q.front();
        q.pop();
        if (ni.isInteger())
          prevSum += ni.getInteger();
        else {
          for (const NestedInteger nextNi : ni.getList())
            q.push(nextNi);
        }
      }
      ans += prevSum;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int depthSumInverse(List<NestedInteger> nestedList) {
    int ans = 0;
    int prevSum = 0;
    Queue<NestedInteger> q = new ArrayDeque<>(nestedList);

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

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def depthSumInverse(self, nestedList: list[NestedInteger]) -> int:
    ans = 0
    prevSum = 0
    q = collections.deque(nestedList)

    while q:
      for _ in range(len(q)):
        ni = q.popleft()
        if ni.isInteger():
          prevSum += ni.getInteger()
        else:
          for nextNi in ni.getList():
            q.append(nextNi)
      ans += prevSum

    return ans