Thursday, May 28, 2015

L Question: Nested List Sum

public int depthSum (List<NestedInteger> input)
{  
    return depthSumHelper(input, 1);
}

private int depthSumHelper(List<NestedInteger> input, int level){
    int sum = 0;

    // look at each nested integer
    for( NestedInteger nestedInt : input){
        if(nestedInt.isInteger()){
            sum += nestedInt.getInteger() * level;
        } else {
            sum += depthSumHelper(nestedInt.getList(), level++);
        }
    }
    return sum;
}

No comments:

Post a Comment