AC code-Recursion way-with returning Depth


  • 0
    Z

    I've saw several discussion code, some of them are brilliant like "add each level integer level times", basically it is the top to bottom solution. My solution is just from bottom to up and return depth each time. All the result add to the num[0], using num[] because it can pass by reference.

    public int depthSumInverse(List<NestedInteger> nestedList) {
       int[] num = new int[1];
       helper(nestedList, num);
       return num[0];
    }
    
    private int helper(List<NestedInteger> nestedList, int[] num){
        
        int intSum = 0;
        int depth = 1;
        
        List<NestedInteger> list = new ArrayList<>();
        
        for(NestedInteger ni: nestedList){
            if(ni.isInteger()){
                intSum += ni.getInteger();
            }
            else{
                list.addAll(ni.getList());
            }
        }
        
        if(!list.isEmpty()){
            depth = Math.max(helper(list, num), depth);
        }
        num[0] += intSum*depth;
        
        return depth + 1;
    }

Log in to reply
 

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