102.二叉树的层序遍历
一、思路:
二叉树层序遍历使用队列:一个结点出队时将它的左右孩子放入队列,依次循环打印(循环条件为队列非空);
当需要按行打印时,需引入last和nlast两个指针,last指向当前行的最后一个结点,nlast指向下一行的最后一个结点(每次指向新入队的结点,该结点一定是目前下一行的最后一个结点);当last指向的结点出队时,令last=nlast即可。
二、代码(c++):
vector<vector<int>> levelOrder(TreeNode* root) {
if(root==NULL) //二叉树为空的特例
return {};
vector<vector<int>> res; //存放结果
vector<int> line; //存放层序遍历的一行
TreeNode *last=root, *nlast, *r=root; //last指向当前行最后一个元素,nlsat指向下一行最后一个元素
queue<TreeNode*> print_q; //层序遍历的队列
print_q.push(root); //将根节点放入队列
while(print_q.size()) //循环条件为队列非空
{
line.push_back(print_q.front()->val); //存放队列首元素
TreeNode *r=print_q.front(); //记录队首元素
print_q.pop(); //首元素出队
if(r->left) //如果结点非空,将结点的左孩子放入队列
{
print_q.push(r->left);
nlast=r->left; //nlast始终跟踪新入队的结点
}
if(r->right)
{
print_q.push(r->right);
nlast=r->right;
}
if(r==last) //当last指向的结点出队时,令last=nlast
{
last=nlast;
res.push_back(line); //line结束记录并放入res中
vector<int> n;
line=n; //将line置为空
}
}
return res;
}