Nested List Weight Sum

题目
Given a nested list of integers, return the sum of all integers in the list weighted by their depth.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

答案

class Solution {
    public int depthSum(List nestedList) {
        return recur(nestedList, 1);
    }
    
    public int recur(List nestedList, int depth) {
        int total = 0;
        for(int i = 0; i < nestedList.size(); i++) {
            NestedInteger ni = nestedList.get(i);
            if(ni.isInteger()) {
                total += depth * ni.getInteger();
            }
            else {
                total += recur(ni.getList(), depth + 1);
            }
        }
        return total;
    }
}

你可能感兴趣的:(Nested List Weight Sum)