using two stacks...


  • 0
    class Solution {
    public:
        stack<std::vector<NestedInteger>::iterator> stk_b;
        stack<std::vector<NestedInteger>::iterator> stk_e;
        int depthSum(vector<NestedInteger>& nestedList) {
            if(nestedList.empty()) return 0;
            int sum = 0;
            stk_b.push(nestedList.begin());
            stk_e.push(nestedList.end());
            while(!stk_b.empty()){
                if(stk_b.top() == stk_e.top()){
                    stk_b.pop();
                    stk_e.pop();
                }else{
                    auto itr = stk_b.top()++;
                    if(itr->isInteger()){
                        sum+= itr->getInteger()*stk_b.size();
                    }else{
                        stk_b.push(itr->getList().begin());
                        stk_e.push(itr->getList().end());
                    }
                }
            }
            return sum;
        }
    };
    

Log in to reply
 

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