public class Solution {
public int depthSum(List<NestedInteger> nestedList) {
if(nestedList == null) return 0;
return depthSum(nestedList, 1);
}
public int depthSum(List<NestedInteger> nestedList, int depth) {
int sum = 0;
for(NestedInteger n : nestedList){
if(n.isInteger()){
sum += depth*n.getInteger();
}else{
sum += depthSum(n.getList(), depth+1);
}
}
return sum;
}
}
Java solution using recursion


@mailtosunny85 I tried to replace n.isInteger() with n.getList()==null. I think both are checking whether n is a integer, but apparently the latter won't work. I am wondering why... Thanks!!