share 3ms cpp solution using only one queue


  • 0
    I
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> ret {};
            queue<TreeNode*> q {};
            
            if (root) {
                q.push(root);
                while (!q.empty()) {
                    ret.push_back({});
                    q.push(nullptr);    //separate
                    while (q.front()) {
                        ret.at(ret.size()-1).push_back(q.front()->val);
                        if (q.front()->left) q.push(q.front()->left);
                        if (q.front()->right) q.push(q.front()->right);
                        q.pop();
                    }
                    q.pop();    //pop separate sign
                }
            }
            return ret;
        }
    };
    

Log in to reply
 

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