Nested List Weight Sum II

medium dfs bfs

Problem

Given a nested list, weight integers by depthFromBottom — leaves at the deepest level get weight 1, the root level gets the max depth.

Input[1,[4,[6]]]
Output17
depths 3,2,1 → 1·3 + 4·2 + 6·1 = 17.

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