在队列里加一个for循环,循环次数为当前队列 长度,这样每次循环后,出队的都是当前层的节点。
/**
* 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) {
vector<vector<int>>res;
if(root==nullptr) return res;
queue<TreeNode*>q;
q.push(root);
while(!q.empty())
{
vector<int>temp;
int n=q.size();
for(int i=0;i<n;i++)
{
TreeNode*front=q.front();
temp.push_back(front->val);
q.pop();
if(front->left!=nullptr){
q.push(front->left);
}
if(front->right!=nullptr){
q.push(front->right);
}
}
res.push_back(temp);
}
return res;
}
};