Java solution using recursion

  • 0
    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){
                    sum += depth*n.getInteger();
                    sum += depthSum(n.getList(), depth+1);
            return sum;

  • 0

    @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!!

Log in to reply

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