c++ level order traversal


  • 0
    J
    class Solution {
    public:
        int depthSum(vector<NestedInteger>& nestedList) {
            queue<NestedInteger> q;
            int len = nestedList.size();
            for(int i=0; i<len; i++)
            {
                q.push(nestedList[i]);
            }
            int level=1;
            int sum=0;
            while(!q.empty())
            {
                int sz = q.size();
                for(int i=0; i<sz; i++)
                {
                    NestedInteger elem = q.front();
                    q.pop();
                    if(elem.isInteger())
                        sum+=level*elem.getInteger();
                    else
                    {
                        vector<NestedInteger> newList = elem.getList();
                        for(auto item: newList)
                        {
                            q.push(item);
                        }
                    }
                }
                level++;
            }
            return sum;
        }
    };
    

Log in to reply
 

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