C++ recursion


  • 0
    T
    class Solution {
    public:
        void depthSumInverseHelper(vector<NestedInteger>& nestedList, std::unordered_map<int,int>& res, int level) {
            
            for(auto elem:nestedList){           
                if(elem.isInteger())
                    res[level] += elem.getInteger();
                else
                    depthSumInverseHelper(elem.getList(),res,level+1); 
            }   
        }
        
        int depthSumInverse(vector<NestedInteger>& nestedList){
            
            std::unordered_map<int,int> res;
            depthSumInverseHelper(nestedList,res,1);
    
            //calculate result
            int depth = INT_MIN;
            for(auto level:res)
                depth = std::max(depth,level.first);
            int sum=0;
            for(auto level:res)
                sum += level.second * (depth-level.first+1);
    
            return sum;   
        }
        
        
    };
    
    
    
    

Log in to reply
 

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