Easy-to-Understand Recursive Solution with Depth Parameter


  • 0
    G

    Inspired by solutions from previous question, I first find the depth of given nestedList, then use the depth as weight to calculate the sum.

    public class Solution {
    
        public int depthSumInverse(List<NestedInteger> nestedList) {
            int depth = findDepth(nestedList, 1);
            return depthSum(nestedList, depth);
        }
        
        public int findDepth(List<NestedInteger> nestedList, int curDepth) {
            int res = 0;
            for(NestedInteger list: nestedList) {
                if(!list.isInteger()) { 
                    res = Math.max(res, findDepth(list.getList(), curDepth+1));
                }
            }
            return Math.max(res, curDepth);
        }
        
        public int depthSum(List<NestedInteger> nestedList, int depth) {
            int res = 0;
            for(NestedInteger list: nestedList) {
                if(list.isInteger()) res += list.getInteger()*depth;
                if(!list.isInteger()) res += depthSum(list.getList(), depth-1);
            }
            return res;
        }
    }
    

Log in to reply
 

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