Java recursive solution


  • 0
    L
    public class Solution {
        public int depthSum(List<NestedInteger> nestedList) {
            return depthSum(nestedList, 1);
            
        }
        
         public int depthSum(List<NestedInteger> nestedList, int depth) {
             if(nestedList == null || nestedList.size() == 0) {
                 return 0;
             }
            int results = 0;
            for(NestedInteger integer: nestedList) {
                results += (integer.isInteger() ? integer.getInteger() * depth : 0) + depthSum(integer.getList(), depth + 1);
            }
            return results;
        }
    }
    

Log in to reply
 

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