LeetCode Solutions

364. Nested List Weight Sum II

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  int depthSumInverse(vector<NestedInteger>& nestedList) {
    int ans = 0;
    int prevSum = 0;
    queue<NestedInteger> q{{begin(nestedList), end(nestedList)}};

    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;
  }
};
			

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;
  }
}