class Solution {
public:
vector<vector<int>> res;
void bfs(TreeNode* root)
{
queue<TreeNode*> q;
q.push(root);
int last=0;
while(!q.empty())
{
vector<int> level;
int len=q.size();//执行这行时,队列里存储的节点都是哥们,同一层的
while(len--)//遍历所有同一层的节点
{
auto t=q.front();
q.pop();
level.push_back(t->val);
if(t->left) q.push(t->left);//这里要判断一下,只加入非空节点
if(t->right) q.push(t->right);//如果不判断,当同一层全是空的加入到队列中,最终level也是空的,res加入时就要特判一下防止加入空的level
}
res.push_back(level);
}
return;
}
vector<vector<int>> levelOrder(TreeNode* root) {
if(!root)
return res;
bfs(root);
return res;
}
};
标签:return,level,res,层序,push,vector,二叉树,102,root
From: https://www.cnblogs.com/tangxibomb/p/17420361.html