[practice JS] a plain solution


  • 0
    M
    /**
     * @param {NestedInteger[]} nestedList
     * @return {number}
     */
    var depthSum = function(nestedList) {
        var sumList = function(nestedList, level) {
            var sum = 0;  // sum for current nested list
            for (var i = 0; i < nestedList.length; ++i) {
                if (nestedList[i].isInteger()) {
                    sum += level * nestedList[i].getInteger();
                } else {
                    sum += sumList(nestedList[i].getList(), 1 + level);
                }
            }
            return sum;
        };
        return sumList(nestedList, 1);
    };
    

Log in to reply
 

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