C++ easy stack (can be changed to queue) solution with bfs


  • 0
    N
    class Solution {
    public:
        int depthSum(vector<NestedInteger>& nestedList) {
            stack<pair<NestedInteger, int>> boxes; 
            int answer = 0;
            if (nestedList.empty())
                return 0;
            
            for (auto he : nestedList) {
                if (he.isInteger())
                    answer += he.getInteger();
                else {
                    boxes.push(make_pair(he, 2));
                }
            }
            
            while(!boxes.empty()) {
                vector<NestedInteger> list = boxes.top().first.getList();
                int level = boxes.top().second;
                boxes.pop();
                        
                for (auto tmp : list) {
                    if (tmp.isInteger())
                        answer += tmp.getInteger() * level;
                    else
                        boxes.push(make_pair(tmp, level + 1));
                }
            }
            
            return answer;
        }
    };
    

Log in to reply
 

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