c++ two pass solution


  • 0
    B

    dfs find the max depth, and then solve it as in previous problem decreasingly

    class Solution {
    public:
        int lvl=0;
        
        int dfs(NestedInteger &nest, int depth){
            int sum=0;
            if(nest.isInteger()) sum+=nest.getInteger()*depth;
            else{
                for(auto n:nest.getList()){
                    sum+=dfs(n, depth-1);
                }
            }
            return sum;
        }
        
        void findmax(NestedInteger &nest, int depth){
            lvl=max(lvl, depth);
            if(!nest.isInteger()){
                for(auto n:nest.getList()){
                    findmax(n, depth+1);
                }
            }
        }
        
        int depthSumInverse(vector<NestedInteger>& nestedList) {
            int sum=0;
            
            for(int i=0;i<nestedList.size();i++)
                findmax(nestedList[i], 1);
                
            for(int i=0;i<nestedList.size();i++){
                sum+=dfs(nestedList[i],lvl);    
            }
            
            return sum;
        }
    };
    

Log in to reply
 

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