C++ Solution, Using only one queue with nullptr mark


  • 1
    Y
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            if(root==NULL){return vector<vector<int>>();}
            vector<vector<int>> result;
            vector<int> temp;
            queue<void*> que;
            que.push(root);
            que.push(nullptr);
            while(que.size()>0)
            {
                if(que.front()==nullptr)
                {
                    que.pop();
                    result.push_back(temp);
                    temp.clear();
                    if(que.size()!=0)
                        que.push(nullptr);
                    continue;
                }
                TreeNode* tNo=reinterpret_cast<TreeNode*>(que.front());
                temp.push_back(tNo->val);
                if(tNo->left){que.push(tNo->left);}
                if(tNo->right){que.push(tNo->right);}
                que.pop();
            }
            return result;
        }
    };
    

Log in to reply
 

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