Simple java O(n) recursive solution


  • 0
    O
    public class Solution {
        public int depthSum(List<NestedInteger> nestedList) {
            return findRecursiveSum(nestedList, 1);
        }
        
        public int findRecursiveSum(List<NestedInteger> list, int depth){
            
            Iterator<NestedInteger> it = list.iterator();
            int result = 0;
            while(it.hasNext()){
                NestedInteger element = it.next();
                if (!element.isInteger()){
                    result += findRecursiveSum(element.getList(), depth + 1);
                }else{
                    result += (element.getInteger() * depth);
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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