Java dfs solution, O(n)


  • 0
    M
    public class Solution {
        public int depthSum(List<NestedInteger> nestedList) {
            if(nestedList == null || nestedList.size()==0) return 0;
            return dfs(1, nestedList);
        }
        
        private int dfs(int depth, List<NestedInteger> nestedList) {
            int sum = 0;
            for(NestedInteger nestInt : nestedList){
                if(nestInt.isInteger()){
                    sum += nestInt.getInteger() * depth;
                } else {
                    List<NestedInteger> subList = nestInt.getList();
                    sum += dfs(depth+1, subList);
                }
            }
            return sum;
        }
    }
    

Log in to reply
 

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