Java solution using recursion


  • 0
    M
    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;
        }
    }
    

  • 0
    O

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