Java - Easy to understand solution using recursion

  • 0

    This might not be efficient, but it is easy to understand . Let me know if you have any questions.

    public class Solution {
        public int depthSumInverse(List<NestedInteger> nestedList) {
            if(nestedList.size()==0) return 0;
            List<List<Integer>> list = new ArrayList<>();
            helper(nestedList, 0,list);
            int result = 0;
            int n = list.size();
            for(int i = 0;i<n;i++){
                List<Integer> l = list.get(i);
                int power = n-i;
                for(int j: l){
                    result+= (power*j);
            return result;
        private void helper(List<NestedInteger> nestedList, int level, List<List<Integer>> list){
                list.add(new ArrayList<>());    
            for(int i = 0;i<nestedList.size();i++){
                NestedInteger j = nestedList.get(i);
                    helper(j.getList(),level+1, list);

Log in to reply

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