# My 4ms C++ solution using one queue, beats 78.81%

• /**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {

vector<vector<int>> tree;
vector<int> level;

if(root == NULL)
return tree;

queue<TreeNode *> q;
int currLevel = 1;
int nextLevel = 0;

q.push(root);
while(!q.empty())
{
TreeNode* node = q.front();
q.pop();
currLevel--;
level.push_back(node->val);
if(node->left)
{
q.push(node->left);
nextLevel++;
}
if(node->right)
{
q.push(node->right);
nextLevel++;
}
if(currLevel == 0)
{
tree.push_back(level);
level.clear();
currLevel = nextLevel;
nextLevel = 0;
}
}

return tree;
}
};

• That's a neat concept!
Although I feel like my solution is clearer, takes the same amount of time, and actually more memory efficient (using emplace instead of push_back).

{
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ret;
if (root == nullptr) return ret;
deque<TreeNode*> s;
s.push_back(root);
s.push_back(nullptr);
ret.emplace_back();
while (!s.empty()) {
auto front = s.front();
s.pop_front();
if (front == nullptr) {
if (!s.empty()) {
ret.emplace_back();
s.push_back(nullptr);
}
continue;
}

ret.back().push_back(front->val);
if (front->left) s.push_back(front->left);
if (front->right) s.push_back(front->right);
}
}
}

• Thank u, smart ideal!

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