Super easy 2ms Java solution


  • 0
    D

    Like many similar problems, we can use either stack or recursion to unwrap any nested data structure.

    public int depthSum(List<NestedInteger> nestedList) {
        return dfs(nestedList, 1, 0);
    }
    
    private int dfs(List<NestedInteger> nestedList, int w, int res) {
        for (NestedInteger n : nestedList) {
            res += n.isInteger() ? n.getInteger() * w : dfs(n.getList(), w + 1, 0);
        }
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.