``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode() : val(0), left(nullptr), right(nullptr) {}
*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode *> queue;
vector<vector<int>> level;
queue.push(root);

while(!queue.empty())
{
vector<int> tmp;

queue.pop();
level.push_back(tmp);
}

return level;
}
};``````

``````Wrong Answer
Runtime: 0 ms
[3,9,20,null,null,15,7]
Output
[[3],[9],[20],[15],[7]]
Expected
[[3],[9,20],[15,7]]``````

WA的原因是我们没有在vector中按层次保存节点，而是每个结点一个vector,如何修复这个问题呢?

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode() : val(0), left(nullptr), right(nullptr) {}
*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode *> queue;
vector<vector<int>> level;
if(root) queue.push(root);

while(!queue.empty())
{
vector<int> res;
int n = queue.size();
for(int i = 0;i < n;i++)
{
TreeNode * elem = queue.front();
res.push_back(elem->val);
if(elem->left) queue.push(elem->left);
if(elem->right) queue.push(elem->right);

queue.pop();
}

if(res.size() > 0)
level.push_back(res);
}

return level;
}
};``````

``````34 / 34 test cases passed.
Status: Accepted
Runtime: 0 ms
Memory Usage: 12.8 MB
Submitted: 1 minute ago``````