Nested List Weight Sum

medium dfs tree

Problem

Given a nested list of integers, return the sum of each integer multiplied by its depth.

Input[[1,1],2,[1,1]]
Output10
1·2 + 1·2 + 2·1 + 1·2 + 1·2 = 10.

def depth_sum(nested):
    def go(items, depth):
        s = 0
        for x in items:
            if isinstance(x, int): s += x * depth
            else: s += go(x, depth + 1)
        return s
    return go(nested, 1)
function depthSum(nested) {
  function go(items, depth) {
    let s = 0;
    for (const x of items) {
      if (Array.isArray(x)) s += go(x, depth + 1);
      else s += x * depth;
    }
    return s;
  }
  return go(nested, 1);
}
class Solution {
    public int depthSum(List nested) { return go(nested, 1); }
    int go(List items, int depth) {
        int s = 0;
        for (NestedInteger x : items) {
            if (x.isInteger()) s += x.getInteger() * depth;
            else s += go(x.getList(), depth + 1);
        }
        return s;
    }
}
class Solution {
    int go(vector& items, int depth) {
        int s = 0;
        for (auto& x : items) {
            if (x.isInteger()) s += x.getInteger() * depth;
            else s += go(x.getList(), depth + 1);
        }
        return s;
    }
public:
    int depthSum(vector& nested) { return go(nested, 1); }
};
Time: O(n) Space: O(d)