求二叉树的层序遍历题解,bfs
// write code here
vector<vector<int>> vect;
if (root==NULL)
{
return vect;
}
//边界检测
queue<TreeNode*> que;
//创建队列
que.push(root);
//根节点入队
while (!que.empty())//队列不为空,继续循环
{
int LevelNum = que.size();
//记录每层节点的个数
vector<int> vec;
//记录每层节点的元素
for (int i = 0; i < LevelNum; i++)
{
TreeNode* t = que.front();
//接收队列中头结点元素
que.pop();
//删除头结点元素
vec.push_back(t->val);
//将值存放到数组中
if (t->left!=nullptr)
{
que.push(t->left);
//如果左子树不为空,将左子树的根节点装入队列
}
if (t->right!=nullptr)
{
que.push(t->right);
//如果右子树不为空,将右子树的根节点装入队列
}
}
vect.push_back(vec);
}
return vect;
}