Same DFS method in nested list weight sum I, but with a little trick.


  • 0
    T

    We can obtained inverse sum from computing total sum and sum from Weight sum I.

    public class Solution {
        int deepest = 0;
        int sum2 = 0;
    
        private int helper(NestedInteger cur, int depth){
            int sum = 0;
            if(cur.isInteger()){
                sum += cur.getInteger()*depth;
                sum2 += cur.getInteger();
                deepest = Math.max(deepest, depth);
            }else{
                List<NestedInteger> nexts= cur.getList();
                for(NestedInteger next : nexts){
                    sum += helper(next, depth+1);
                }
            }
            return sum;
        }
        
        public int depthSumInverse(List<NestedInteger> nestedList) {
            int depth = 1;
            int sum1 = 0;
            for(NestedInteger cur: nestedList){
                sum1 += helper(cur, 1);
            }
           
            return sum2*(deepest+1)-sum1;
        }
    }
    

Log in to reply
 

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